gpt4 book ai didi

javascript - 如何为 Canvas "drawing style"应用程序获取平滑的鼠标事件?

转载 作者:行者123 更新时间:2023-11-30 18:38:42 25 4
gpt4 key购买 nike

我正在尝试为绘图风格的应用程序在屏幕上平滑地移动鼠标。更具体地说,它是一个“粉末玩具”。这意味着,它是逐像素绘制的,所以我不能做一些线条技巧。我最初想检查 mouse down 和 mouse up 然后在我的游戏“更新”循环中放一些东西让它在屏幕上绘制像素但是当我发现我无法直接获取鼠标 X 和鼠标 Y 时没有成功事件触发。

那么有没有人知道一种平滑鼠标移动的方法,我目前使用的方法是使用导致此问题的 mousemove 事件:

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

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

谢谢,

最佳答案

看起来你正在做一个沙克隆世界,所以我想你需要矩形。我用了Bresenham's line algorithm绘制点。基本上 onmousedown 它开始绘画。然后 onmousemove 它将当前坐标与上一个坐标进行比较并绘制两者之间的所有点。

Live Demo

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;

}
}

关于javascript - 如何为 Canvas "drawing style"应用程序获取平滑的鼠标事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7478501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com