Get mouse coordinates in JavaScript Canvas

From The IT Community
Jump to: navigation, search




If you want to get the coordinates of the mouse pointer inside a JavaScript Canvas on your web site, have a look at the following script:

<html>
 <head>
   <title>The IT Community Script</title>
 </head>
 <body>
 <canvas id="myCanvas" width="1024" height="768"></canvas>
 <script type='text/javascript'>

       var mousex = 1;
       var mousey = 1;
       var canvas = document.getElementById('myCanvas');
       var context = canvas.getContext('2d'); 

       function getMousePos(mycanvas, evt) {
         var rect = mycanvas.getBoundingClientRect();
         mousey= evt.clientY - rect.top;
         mousex= evt.clientX - rect.left; }

       canvas.addEventListener('mousemove', function(evt) {getMousePos(canvas, evt);}, false);
 </body>
</html>

mousex and mousey will always hold the coordinates of your mouse pointer, as long as it is inside the canvas.



Was this article helpful? Then please donate to keep The IT Community alive...

If you found this article helpful please share it, comment and help others by writing your own article.






Translate this page:




Articles found in the same category:
(max. 20 shown)