I have a simple Canvas drawing app. Sometimes the lineTo() command produces a line of less coordinates and the drawing has many edges:
I'm using the latest firefox, is it because the connection is bad or my computer is buisy? Is there a work around? Here is my code: JS FIDDLE
beginPath();
moveTo(this.X, this.Y);
lineTo(e.pageX , e.pageY );
strokeStyle = "rgb(0,0,0)";
ctx.lineWidth=3;
stroke();
It's responding as fast as it can. Your browser will deliver events as fast as it can, but it's not in any way guaranteed to be able to track you moving the mouse. A lot has to do with the load on the client machine.
edit — here is a modified fiddle demonstrating some ways you might make it a little better. That version keeps a separate "points" queue that draws new points every 50 milliseconds. That makes it so that the "mousemove" handler only has to log the point coordinates from the event, and the drawing code can do a bunch of points with one canvas update when the mouse is moving quickly. It's still not perfect.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;
canvas.addEventListener('mousedown', function(e) {
this.down = true;
points.setStart(e.pageX, e.pageY);
}, 0);
canvas.addEventListener('mouseup', function() {
this.down = false;
}, 0);
canvas.addEventListener('mousemove', function(e) {
if (this.down) {
points.newPoint(e.pageX, e.pageY);
}
}, 0);
var points = function() {
var queue = [], qi = 0;
var ctx = canvas.getContext('2d');
function clear() {
queue = [];
qi = 0;
}
function setStart(x, y) {
clear();
newPoint(x, y);
}
function newPoint(x, y) {
queue.push([x, y]);
}
function tick() {
var k = 20; // adjust to limit points drawn per cycle
if (queue.length - qi > 1) {
ctx.beginPath();
if (qi === 0)
ctx.moveTo(queue[0][0], queue[0][1]);
else
ctx.moveTo(queue[qi - 1][0], queue[qi - 1][1]);
for (++qi; --k >= 0 && qi < queue.length; ++qi) {
ctx.lineTo(queue[qi][0], queue[qi][1]);
}
ctx.strokeStyle = "rgb(0,0,0)";
ctx.lineWidth = 3;
ctx.stroke();
}
}
setInterval(tick, 50); // adjust cycle time
return {
setStart: setStart,
newPoint: newPoint
};
}();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With