I wrote a little drawing script (canvas) for this website: http://scri.ch/
When you click on the document, every mousemove
event basically executes the following:
- Get coordinates.
- context.lineTo()
between this point and the previous one
- context.stroke()
the line
As you can see, if you move the cursor very fast, the event isn’t triggering enough (depending on your CPU / Browser / etc.), and a straight line is traced.
In pseudocode:
window.addEventListener('mousemove', function(e){
myContext.lineTo(e.pageX, e.pageY);
myContext.stroke();
}, false);
This is a known problem, and the solution is fine, but I would like to optimize that.
So instead of stroke()
each time a mousemove event is triggered, I put the new coordinates inside an array queue, and regularly draw / empty it with a timer.
In pseudocode:
var coordsQueue = [];
window.addEventListener('mousemove', function(e){
coordsQueue.push([e.pageX, e.pageY]);
}, false);
function drawLoop(){
window.setTimeout(function(){
var coords;
while (coords = coordsQueue.shift()) {
myContext.lineTo(coords[0], coords[1]);
}
myContext.stroke();
drawLoop();
}, 1000); // For testing purposes
}
But it did not improve the line. So I tried to only draw a point on mousemove
. Same result: too much space between the points.
It made me realize that the first code block is efficient enough, it is just the mousemove
event that is triggering too slowly.
So, after having myself spent some time to implement a useless optimization, it’s your turn: is there a way to optimize the mousemove
triggering speed in DOM scripting?
Is it possible to “request” the mouse position at any time?
Thanks for your advices!