如何固定鼠标相对于画布父级的位置?

时间:2019-06-23 05:16:33

标签: javascript vue.js canvas vue-component

我正在尝试使用此Codepen的Vuejs Draw Canvas作为组件。一切正常,但鼠标位置与我认为的窗口有关。因此,在绘制时,只有在画布是窗口大小(宽度,高度)的情况下,如果光标和绘制位置没有很大的差别,它的工作效果就很好。

我尝试将画布的宽度和高度设置为offset而不是像

这样的窗口
setSize() {
   this.c.width = this.c.offsetWidth;
   this.c.height = this.c.offsetHeight - 60;
}

和具有以下代码的鼠标位置,如此SO答案

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

但是它没有改变结果。因此,将其还原并添加到代码沙箱中。如果有人可以帮助我找出这里的问题?我知道它与鼠标位置有关,但不确定确切位置。

这里是试图修复的演示的codesandbox链接。

2 个答案:

答案 0 :(得分:0)

我使用这两种方法(不确定是否进一步挖掘它们为何不相同的原因):

canv = document.getElementById("id-of-canvas-object")

function mouseLocation(e)
{
 if (e.preventDefault)
    e.preventDefault();
 var x = e.PageX; var y = e.PageY;
// in one instance
 var relativeX = x - canv.offsetLeft;
 var relativeY = y - canv.offsetTop;
// in another instance
  var rect = canv.getBoundingClientRect();
  relativeX = x - rect.left;
  relativeY = y - rect.top;
}

答案 1 :(得分:0)

在您共享的示例中,您在重新定位光标时并没有计算偏移量,而是减去了60px的偏移量,由于控件的固定位置,这是不必要的。

在线上只有2个区别:234和239

setSize() {
  this.c.width = this.c.offsetWidth;
  this.c.height = this.c.offsetHeight; // <--- HERE i removed the -60px offset
}

moveMouse(e) {
  let x = e.offsetX;
  let y = e.offsetY + 60; // <--- HERE i added the 60px offset
  // the ´e.offsetY´ is relative to the canvas but you have an offset
  // for the controls that is moving the cursor (the little dot) to the top

  var cursor = document.getElementById("cursor");

  cursor.style.transform = `translate(${x}px, ${y}px)`;
}

这里固定了示例:Fixed codesandbox

注意:我建议更改控件的固定位置,并使用固定的高度和宽度值管理所有内容,或者使用flexbox根据需要扩展画布。