如何为画布“绘制样式”获得平滑的鼠标事件应用程序

How to get smooth mouse events for a canvas "drawing style" app?

本文关键字:平滑 鼠标 应用程序 事件 绘制样式 样式 绘制      更新时间:2023-09-26

我正试图使鼠标在屏幕上流畅地移动绘画风格的应用程序。更具体地说,它是一个"粉末玩具"。这意味着,它一个像素一个像素地画所以我不能做一些线条技巧。我最初想的是检查鼠标上下,然后在游戏"更新"循环中添加一些内容,使其在屏幕上绘制像素,但当我发现我无法在没有事件触发的情况下直接获得鼠标X和鼠标Y时,这就行不通了。

那么,有没有人知道一种平滑鼠标移动的方法,我目前使用的方法是使用mousemove事件,这会导致以下情况:

http://img1.uploadscreenshot.com/images/orig/9/26119184415-orig.jpg

(注意像素是如何分散的)

谢谢你,

看起来你在做一个沙子克隆的世界,所以我想你需要rects。我用布里森汉姆的直线算法绘制了这些点。基本上是onmousedown,它开始绘画。然后onmousemove将当前坐标与最后一个坐标进行比较,并绘制出两者之间的所有点。

现场演示

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    painting = false,
    lastX = 0,
    lastY = 0;
canvas.width = canvas.height = 600;
ctx.fillRect(0, 0, 600, 600);
canvas.onmousedown = function(e) {
    if (!painting) {
        painting = true;
    } else {
        painting = false;
    }
    ctx.fillStyle = "#ffffff";
    lastX = e.pageX - this.offsetLeft;
    lastY = e.pageY - this.offsetTop;
};
canvas.onmousemove = function(e) {
    if (painting) {
        mouseX = e.pageX - this.offsetLeft;
        mouseY = e.pageY - this.offsetTop;
        // find all points between        
        var x1 = mouseX,
            x2 = lastX,
            y1 = mouseY,
            y2 = lastY;

        var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
        if (steep){
            var x = x1;
            x1 = y1;
            y1 = x;
            var y = y2;
            y2 = x2;
            x2 = y;
        }
        if (x1 > x2) {
            var x = x1;
            x1 = x2;
            x2 = x;
            var y = y1;
            y1 = y2;
            y2 = y;
        }
        var dx = x2 - x1,
            dy = Math.abs(y2 - y1),
            error = 0,
            de = dy / dx,
            yStep = -1,
            y = y1;
        if (y1 < y2) {
            yStep = 1;
        }
        for (var x = x1; x < x2; x++) {
            if (steep) {
                ctx.fillRect(y, x, 1, 1);
            } else {
                ctx.fillRect(x, y, 1, 1);
            }
            error += de;
            if (error >= 0.5) {
                y += yStep;
                error -= 1.0;
            }
        }

        lastX = mouseX;
        lastY = mouseY;
    }
}