我试图在位于具有自动边距的 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);
}