鼠标在canvas里的相对坐标

  1. <canvas id="canvas"></canvas>
  1. //获取相对于canvas的坐标
  2. function captureMouse(element) {
  3. let mouse = { x: 0, y: 0 };
  4. element.addEventListener('mousemove', function (event) {
  5. let x, y;
  6. if (event.pageX || event.pageY) {
  7. x = event.pageX;
  8. y = event.pageY;
  9. } else {
  10. x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
  11. y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
  12. }
  13. x -= element.offsetLeft;
  14. y -= element.offsetTop;
  15. mouse.x = x;
  16. mouse.y = y;
  17. }, false);
  18. return mouse;
  19. }
  20. var canvas = document.getElementById("canvas");
  21. var mouse = captureMouse(canvas); //鼠标在画布的相对坐标,随着鼠标在画布上移动实时变化