Getting cursor position in a canvas without jQuery

杀马特。学长 韩版系。学妹 提交于 2019-12-01 05:57:25

问题


I am trying to learn how to use the HTML canvas element, and naturally, I am making a drawing application. So, I have the code set up for the actual drawing and animating part of the app, but I am not sure how to approach getting the position of the mouse cursor. I really would prefer not to use jQuery, for I would rather not want to learn all of what it does and have to go through the process of getting it set up. Thanks for any help!


回答1:


  function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect(), root = document.documentElement;

    // return relative mouse position
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {
      x: mouseX,
      y: mouseY
    };
  }

  window.onload = function() {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    canvas.addEventListener('mousemove', function(evt) {
      var mousePos = getMousePos(canvas, evt);
      var message = "Mouse position: " + mousePos.x + "," + mousePos.y;
      alert(message);
    }, false);
  };

Source




回答2:


When using it to draw on a canvas, I prefer this code:

    function getMousePos(canvas, event)
{
    var mouseX = event.pageX - canvas.offsetLeft;
    var mouseY = event.pageY - canvas.offsetTop;
    return {
        x: mouseX,
        y: mouseY };
}

This was the code that I used to avoid scrolling, position and other issues I got with getting the correct position of the mouse.



来源:https://stackoverflow.com/questions/12772943/getting-cursor-position-in-a-canvas-without-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!