show mouse coordinates over canvas using pure javascript in tooltip form? - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

show mouse coordinates over canvas using pure javascript in tooltip form?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){/*from w  ww.ja v a  2 s . co m*/
$(function() {
      var canvas = $('#canvas').get(0);
      var ctx = canvas.getContext('2d');
      var w = h = canvas.width = canvas.height = 300;
      ctx.fillStyle = '#000';
      ctx.fillRect(0, 0, w, h);
      canvas.addEventListener('mousemove', function(e) {
        var x = e.pageX - canvas.offsetLeft;
        var y = e.pageY - canvas.offsetTop;
        var str = 'X : ' + x + ', ' + 'Y :' + y;
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, w, h);
        ctx.fillStyle = '#222';
        ctx.fillRect(x + 10, y + 10, 80, 25);
        ctx.fillStyle = '#0099f9';
        ctx.font = 'bold 20px verdana';
        ctx.fillText(str, x + 20, y + 30, 60);
      }, 0);
    });
    }

      </script> 
   </head> 
   <body> 
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
      <canvas id="canvas"></canvas>  
   </body>
</html>

Related Tutorials