I'm trying to make smooth mouse movements across the screen for a drawing style app. More specifically its a "Powder toy". What this means is, it draws pixel by pixel so I cant do some line开发者_运维百科 trickery. I was initially thinking of checking mouse down and mouse up then put something in my game "update" loop to make it draw pixels to the screen but that didnt work out when I found I couldn't directly get the mouse X and mouse Y without the events firing.
So does anyone know a way of smooth mouse movements, the way I have at the moment uses the mousemove event which causes this:
http://img1.uploadscreenshot.com/images/orig/9/26119184415-orig.jpg
(Notice how the pixels are spread apart)
Thank you,
Looks like your doing a world of sand clone so I imagine you need rects. I used Bresenham's line algorithm to plot the points. Basically onmousedown
it starts painting. Then onmousemove
it compares the current coordinates with the last coordinates and plots all of the points between.
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;
}
}
精彩评论