绘制的线与鼠标指针偏移

时间:2013-07-15 01:19:35

标签: html5 canvas

如果我向下滚动以查看画布的底部部分,绘图功能仍然有效,但该行不是来自鼠标指针。 http://flamencopeko.net/draw.php http://flamencopeko.net/draw.txt

<canvas id = "can" width = "715" height = "715" 
    style = "position: relative; border: 1px solid; background: #FFFFFF;">
</canvas>

问题是跨浏览器。

2 个答案:

答案 0 :(得分:1)

你的findxy函数使用画布的绝对位置,当你scoll时它不会改变,但是clientX / clientY确实相对于画布发生了变化。

您可以使用getBoundingClientRect()中的信息将鼠标坐标移动到画布坐标空间。

试试这个:

function findxy(res, e) {
var rect = canvas.getBoundingClientRect();

if (res == 'down') {
    prevX = currX;
    prevY = currY;
    currX = e.clientX  - rect.left;
    currY = e.clientY - rect.top

    flag = true;
    dot_flag = true;
    if (dot_flag) {
        ctx.beginPath();
        ctx.fillStyle = x;
        ctx.fillRect(currX, currY, 2, 2);
        ctx.closePath();
        dot_flag = false;
    }
}
if (res == 'up' || res == "out") {
    flag = false;
}
if (res == 'move') {
    if (flag) {
        prevX = currX;
        prevY = currY;
        currX = e.clientX - rect.left;
        currY = e.clientY - rect.top
        draw();
    }
}

}

getBoundingClientRect()将获取画布相对于视图端口的坐标(与clientX / clientY相同),因此不受滚动影响。

答案 1 :(得分:0)

我很确定我知道这里的问题是什么,但我快速查看了您的网站以确定。所以你需要做的就是添加窗口滚动的程度。从我所看到的,它应该插入你的findxy()函数,如下所示:

currX = window.pageXOffset + e.clientX - canvas.offsetLeft;
currY = window.pageYOffset + e.clientY - canvas.offsetTop;

因此,为了解释,来自事件对象的clientX和clientY值计算相对于用户屏幕左上角的鼠标位置,而不是整个页面。这就是为什么我们还需要从窗口对象中添加页面偏移值。

相关问题