我有以下一段代码
canvas1.addEventListener('mousedown', function(e) {
var x = e.clientX - canvas1.getBoundingClientRect().left;
var y = e.clientY - canvas1.getBoundingClientRect().top;
if (rect.currentActiveBox == currentActiveBox) {
// Incase we try to draw another box first clear out the previous box.
console.log('clearing ', rect);
ctx.clearRect(rect.startX - 6 , rect.startY - 6, rect.w + 8, rect.h + 8);
}
rect.startX = x;
rect.startY = y;
isDrawing = true;
rect.currentActiveBox = currentActiveBox;
rects[currentActiveBox] = JSON.parse(JSON.stringify(rect));
});
canvas1.addEventListener('mousemove', function(e) {
if(isDrawing === true) {
// rect.w = (e.pageX - this.offsetLeft) - rect.startX;
// rect.h = (e.pageY - this.offsetTop) - rect.startY ;
rect.w = e.pageX - rect.startX;
rect.h = e.pageY - rect.startY;
ctx.clearRect(rect.startX, rect.startY, rect.w, rect.h);
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
rects[currentActiveBox] = JSON.parse(JSON.stringify(rect));
}
});
然而,这只有在我将鼠标从
top
拖动到 bottom
方式时才有效。如果我尝试从 bottom
up
拖动鼠标,我会得到如下所示的幻影框。
我希望
mousemove
方向不应该改变绘图的方式。有什么明显的我可能会遗漏的东西吗?
它在技术上outside您在坐标中指定的矩形。
因此,在您的
mousemove
功能中,当您clearRect
时,您正在清除红线内部的区域,而不是红线本身。
更进一步,在你的
mousedown
函数中,你做了一些很好的捏造,从左边/顶部开始,然后比标称宽度/高度更宽/更深。
也许尝试捏造你的 mousemove?
例如,你可以试试这个:
...
rect.h = e.pageY - rect.startY;
ctx.clearRect(rect.startX-3, rect.startY-3, rect.w+6, rect.h+6);
ctx.beginPath();
...
如果这不起作用,请尝试用绘制
不同颜色的
clearRect
替换rect
。这样,您可以检查它试图删除的位置,并确保它在您期望的位置。
有几件事:
pageX
和 clientX
不可互换,因此你对 rect.w
和 rect.h
的注释计算(这似乎考虑了元素偏移量,如mousedown
处理程序)是正确的。你可以这样做:
if(isDrawing === true) {
const strokeSize = 3;
// Compute bounding box for all pixels touched by the stroke –
// be sure to get a generous border to cope with antialiasing
const clearLeft = Math.min(rect.startX, rect.startX + rect.w) - strokeSize;
const clearTop = Math.min(rect.startY, rect.startY + rect.h) - strokeSize;
const clearRight = Math.max(rect.startX, rect.startX + rect.w) + strokeSize;
const clearBottom = Math.max(rect.startY, rect.startY + rect.h) + strokeSize;
ctx.clearRect(clearLeft, clearTop, clearRight - clearLeft, clearBottom - clearTop);
rect.w = e.pageX - this.offsetLeft - rect.startX;
rect.h = e.pageY - this.offsetTop - rect.startY;
ctx.beginPath();
// etc
}