present clicked xy points as text? - Javascript Canvas

Javascript examples for Canvas:Text

Description

present clicked xy points as text?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <style id="compiled-css" type="text/css">

body {/*from   w  ww  .  j  a va2  s  .c  o  m*/
   background-color: ivory;
   padding:10px;
}
canvas {
   border:1px solid red;
   float:left;
}
#container {
   width:410px;
}
#log {
   width:100px;
   height:300px;
   float:right;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var canvasMouseX;
        var canvasMouseY;
        var canvasOffset = $("#canvas").offset();
        var offsetX = canvasOffset.left;
        var offsetY = canvasOffset.top;
        var storedPoints = [];
        ctx.strokeStyle = "orange";
        ctx.font = '12px Arial';
        $("#canvas").mousedown(function (e) {
            handleMouseDown(e);
        });
        function handleMouseDown(e) {
            canvasMouseX = parseInt(e.clientX - offsetX);
            canvasMouseY = parseInt(e.clientY - offsetY);
            // Put your mousedown stuff here
            storedPoints.push({
                x: canvasMouseX,
                y: canvasMouseY
            });
            var count = storedPoints.length;
            var X = canvasMouseX - (count < 10 ? 4 : 7);
            ctx.strokeStyle = "orange";
            ctx.fillStyle = "black";
            ctx.lineWidth = 1;
            ctx.beginPath();
            ctx.arc(canvasMouseX, canvasMouseY, 8, 0, 2 * Math.PI, false);
            ctx.fillText(storedPoints.length, X, canvasMouseY + 4);
            ctx.stroke();
            $("#log").html(toHtml());
        }
        function toHtml() {
            htmlPoints = "";
            for (var i = 0; i < storedPoints.length; i++) {
                htmlPoints += "<p>" + storedPoints[i].x + "," + storedPoints[i].y + "</p>"
            }
            return (htmlPoints);
        }
        $("#clear").click(function () {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            storedPoints = [];
            $("#log").html(toHtml());
        });
    });

      </script> 
   </head> 
   <body> 
      <br> 
      <p>Click on canvas to create points as text</p> 
      <br> 
      <button id="clear">Clear Canvas</button> 
      <div id="container"> 
         <canvas id="canvas" width="300" height="300"></canvas> 
         <div id="log"></div> 
      </div>  
   </body>
</html>

Related Tutorials