getting mouse position relative to content area of an element

前端 未结 4 1022
臣服心动
臣服心动 2020-12-15 09:25

When the mouse is moved over an element, I want to get the mouse coordinates of the cursor relative to the top-left of the element\'s content area (this is the area excludin

4条回答
  •  星月不相逢
    2020-12-15 10:02

    I am not sure if this is the best way, or most resource efficient...

    But I would suggest getting X/Y for the canvas tag, width of the border, and padding and using them all together as the offset.

    Edit:

    Use offsetLeft and offsetTop

    Reference: How to Use the Canvas and Draw Elements in HTML5

    var x;
    var y;
    if (e.pageX || e.pageY) { 
      x = e.pageX;
      y = e.pageY;
    }
    else { 
      x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
      y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
    } 
    x -= gCanvasElement.offsetLeft;
    y -= gCanvasElement.offsetTop;
    

提交回复
热议问题