mousemove 事件是否会根据鼠标方向的不同而有所不同?

问题描述 投票:0回答:2

我有以下一段代码

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
方向不应该改变绘图的方式。有什么明显的我可能会遗漏的东西吗?

javascript html dom dom-events
2个回答
0
投票

注意笔划的位置!

它在技术上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。这样,您可以检查它试图删除的位置,并确保它在您期望的位置。


0
投票

有几件事:

  • 正如 ProfDFrancis 指出的那样,您的笔划实际上延伸到了边界框矩形之外,因此您需要扩大清除区域
  • 你正在清除 new 矩形而不是以前的矩形,所以如果指针移动一次超过 1px,你将留下伪影
  • 你的指针偏移量不一致 -
    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
    }

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.