HTML5 Game - Canvas Event Mouse position

Introduction

The mouse event has two properties to show the current location of the mouse cursor:

  • pageX
  • pageY.

By combining these values and the offset of the canvas element, you can get the mouse position on the canvas element.

Demo

ResultView the demo in separate window

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Mouse Position</title>
    <style>#canvas {
  background-color: grey;
}</style>/*ww  w .j a  va 2  s  .  c o  m*/

  </head>
  <body>

    <canvas id="canvas" width="400" height="400"></canvas>
    <aside>Open debugging console in web browser and click mouse.</aside>
    
    <script>
function captureMouse(element) {
  let mouse = {x: 0, y: 0, event: null},
      body_scrollLeft = document.body.scrollLeft,
      element_scrollLeft = document.documentElement.scrollLeft,
      body_scrollTop = document.body.scrollTop,
      element_scrollTop = document.documentElement.scrollTop,
      offsetLeft = element.offsetLeft,
      offsetTop = element.offsetTop;
  
  element.addEventListener('mousemove', function (event) {
    let x, y;
    
    if (event.pageX || event.pageY) {
      x = event.pageX;
      y = event.pageY;
    } else {
      x = event.clientX + body_scrollLeft + element_scrollLeft;
      y = event.clientY + body_scrollTop + element_scrollTop;
    }
    x -= offsetLeft;
    y -= offsetTop;
    
    mouse.x = x;
    mouse.y = y;
    mouse.event = event;
  }, false);
  
  return mouse;
}      
    window.onload = function () {
      let canvas = document.getElementById('canvas'),
          mouse = captureMouse(canvas);

      canvas.addEventListener('mousedown', function () {
        console.log("x: " + mouse.x + ", y: " + mouse.y);
      }, false);
    };
    </script>
  </body>
</html>

Related Topic