0

我试图在位于具有自动边距的 div 中的画布上获取鼠标坐标,但没有成功。我设置了一个小提琴,我希望有人能看到问题所在。

如果我删除边距,画布背后的逻辑是正确的,但边距会因偏移量的尺寸而偏离。

http://jsfiddle.net/mcgraw73/Mfafz/

function init() {
    FGcanvas.addEventListener('mousedown', mouseDown, false);
    FGcanvas.addEventListener('mouseup', mouseUp, false);
    FGcanvas.addEventListener('mousemove', mouseMove, false);
}

function mouseDown(e) {
  rect.startX = e.clientX - FGcanvas.offsetLeft
  rect.startY = e.clientY - FGcanvas.offsetTop;
  drag = true;
}

function mouseUp() {
  drag = false;
}

function mouseMove(e) {
  if (drag) {
    rect.w = (e.clientX - rect.startX) - FGcanvas.offsetLeft; //(event.clientX - rect.start.x) - canvas.offsetLeft
    rect.h = (e.clientY - rect.startY) - FGcanvas.offsetTop;
    FGcontext.clearRect(0,0,FGcanvas.width,FGcanvas.height);
    draw();
  }
}


function draw() {
  FGcontext.clearRect(0,0,FGcanvas.width,FGcanvas.height);
  FGcontext.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}
4

1 回答 1

1

我不太确定,因为我非常依赖 jQuery,但我认为当它是绝对值时,你无法获得元素的偏移值。

那么为什么不从不在 absolute 的父 div 中获取位置呢?我替换了这个:

FGcanvas.offsetLeft
FGcanvas.offsetTop

和 :

document.getElementById('ramRod').offsetLeft
document.getElementById('ramRod').offsetTop

我还删除了您在此处指定的位置:相对:

body, header, aside, footer, div {
    display: block;
    position: relative;
}

它只影响主体,因为您再次为所有其他元素指定它。

希望这有帮助!(这个网站上的第一个答案!)

编辑:哦,是的,忘记了链接,这是我更新的小提琴:http: //jsfiddle.net/ZDXWP/

于 2013-03-19T18:55:20.050 回答