我正在尝试在屏幕上为绘图样式应用程序制作流畅的鼠标移动。更具体地说,它是一个“粉末玩具”。这意味着,它逐个像素地绘制,所以我不能做一些线条欺骗。我最初想的是检查鼠标向下和鼠标向上,然后在我的游戏“更新”循环中放置一些东西,使其在屏幕上绘制像素,但是当我发现我无法直接获取鼠标X和鼠标Y时没有成功事件发生了。
所以有人知道一种平滑的鼠标移动方式,我现在的方式使用mousemove事件导致这种情况:
http://img1.uploadscreenshot.com/images/orig/9/26119184415-orig.jpg
(注意像素如何分开)
谢谢,
答案 0 :(得分:2)
看起来你正在做一个沙子克隆的世界,所以我想你需要rects。我使用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;
}
}