我想做一个小绘画应用程序使用画布。所以我需要找到鼠标在画布上的位置。


当前回答

Mark van Wyk的回答让我找到了正确的方向,但并没有完全解决我的问题。我仍然在另一个元素中包含的元素中绘画。

以下解决了它为我:

        x = e.pageX - this.offsetLeft - $(elem).offset().left;
        y = e.pageY - this.offsetTop - $(elem).offset().top;

换句话说,我简单地堆叠了所有嵌套元素的偏移量

其他回答

Mark van Wyk的回答让我找到了正确的方向,但并没有完全解决我的问题。我仍然在另一个元素中包含的元素中绘画。

以下解决了它为我:

        x = e.pageX - this.offsetLeft - $(elem).offset().left;
        y = e.pageY - this.offsetTop - $(elem).offset().top;

换句话说,我简单地堆叠了所有嵌套元素的偏移量

通过事件可以获得画布内的鼠标坐标。offsetX和事件。下面是一个小片段来证明我的观点:

c=document.getElementById("c"); ctx=c.getContext("2d"); ctx.fillStyle="black"; ctx.fillRect(0,0,100,100); c.addEventListener("mousemove",function(mouseEvt){ // the mouse's coordinates on the canvas are just below x=mouseEvt.offsetX; y=mouseEvt.offsetY; // the following lines draw a red square around the mouse to prove it ctx.fillStyle="black"; ctx.fillRect(0,0,100,100); ctx.fillStyle="red"; ctx.fillRect(x-5,y-5,10,10); }); body { background-color: blue; } canvas { position: absolute; top: 50px; left: 100px; } <canvas id="c" width="100" height="100"></canvas>

基于@Patrick Boos的解决方案,但修复了中间滚动条的潜在问题。

export function getRelativeCoordinates(event: MouseEvent, referenceElement: HTMLElement) {
  const position = {
    x: event.pageX,
    y: event.pageY,
  };

  const offset = {
    left: referenceElement.offsetLeft,
    top: referenceElement.offsetTop,
  };

  let reference = referenceElement.offsetParent as HTMLElement;

  while (reference) {
    offset.left += reference.offsetLeft;
    offset.top += reference.offsetTop;
    reference = reference.offsetParent as HTMLElement;
  }

  const scrolls = {
    left: 0,
    top: 0,
  };

  reference = event.target as HTMLElement;
  while (reference) {
    scrolls.left += reference.scrollLeft;
    scrolls.top += reference.scrollTop;
    reference = reference.parentElement as HTMLElement;
  }

  return {
    x: position.x + scrolls.left - offset.left,
    y: position.y + scrolls.top - offset.top,
  };
}

如果你想获得与一个元素相关的layerX和layerY,也许你可以尝试:

let bbox_rect = document.getElementById("dom-ID").getBoundingClientRect()
let layerX = e.clientX-bbox_rect.left
let layerY = e.clientY-bbox_rect.top

我实现了另一个解决方案,我认为很简单,所以我想和你们分享一下。

所以,对我来说,问题是拖动的div将跳转到0,0的鼠标光标。所以我需要捕捉鼠标在div上的位置来调整div的新位置。

我读取的divs PageX和PageY,并设置的顶部和左侧的根据,然后得到的值,调整坐标,以保持光标在div的初始位置,我使用onDragStart监听器和存储e.nativeEvent.layerX和e.nativeEvent.layerY,只有在初始触发器给你的鼠标位置在可拖动的div。

示例代码:

 onDrag={(e) => {
          let newCoords;
          newCoords = { x: e.pageX - this.state.correctionX, y: e.pageY - this.state.correctionY };
          this.props.onDrag(newCoords, e, item.id);
        }}
        onDragStart={
          (e) => {
            this.setState({
              correctionX: e.nativeEvent.layerX,
              correctionY: e.nativeEvent.layerY,
            });
          }

我希望这能帮助那些和我经历过同样问题的人:)