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:

   <title>The IT Community Script</title>
 <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 -;
         mousex= evt.clientX - rect.left; }

       canvas.addEventListener('mousemove', function(evt) {getMousePos(canvas, evt);}, false);

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)