The problem is that you are drawing the whole path again and again:
function mouseMove(e) {
...
ctx.stroke(); // Draws whole path which begins where mouseDown happened.
}
You have to draw only the new segment of the path (http://jsfiddle.net/jF9a6/). And then ... you have the problem with the 15px width of the line.
So how to solve this? We have to draw the line at once as you did, but avoid painting on top of existing lines. Here is the code: http://jsfiddle.net/yfDdC/
The biggest change is the paths
array. It contains yeah, paths :-) A path is an array of points stored in mouseDown
and mouseMove
functions. New path is created in mouseDown function:
paths.push([pos]); // Add new path, the first point is current pos.
In the mouseMove you add current mouse position to the last path in paths
array and refreshs the image.
paths[paths.length-1].push(pos); // Append point tu current path.
refresh();
The refresh()
function clears the whole canvas, draws the cat again and draws every path.
function refresh() {
// Clear canvas and draw the cat.
ctx.clearRect(0, 0, ctx.width, ctx.height);
if (globImg)
ctx.drawImage(globImg, 0, 0);
for (var i=0; i<paths.length; ++i) {
var path = paths[i];
if (path.length<1)
continue; // Need at least two points to draw a line.
ctx.beginPath();
ctx.moveTo(path[0].x, path[0].y);
...
for (var j=1; j<path.length; ++j)
ctx.lineTo(path[j].x, path[j].y);
ctx.stroke();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…