I'm developing a painter program using HTML5 canvas. I have created a drawing tool where the user drags and moves the mouse.
I have a listener on mousemove
event that draws short lines:
Painter.mainCanvas.beginPath();
Painter.mainCanvas.moveTo(Painter.lastX, Painter.lastY);
Painter.lastX = e.offsetX;
Painter.lastY = e.offsetY;
Painter.mainCanvas.lineTo(Painter.lastX, Painter.lastY);
Painter.mainCanvas.stroke();
Everything works well until I set the global Alpha to < 1. When using this method to draw, the end dot is also start dot. So the dot is drawn twice. And because we have transparent color, the dot now has different color with other dots in line.
I tried another method that when mousemove fires, it only uses lineTo()
and stroke()
when mouseup fires.
This solves the double drawing problem, but also introduces a new problem: when user intend to draw same dot twice, ie, cross line without mouseup, the dot won't be drawn twice. Because lineTo()
function won't draw a dot twice without stroke between.
lineTo
orstroke
. Instead, to make lines intersected, you need to draw each line POINT BY POINT. See this: losingfight.com/blog/2007/08/18/… – EastmangetImageData
onmousedown
, then simplyputImageData(oldData)
and thenstroke
. That way, you reset the whole canvas to before a stroke was made, and then re-draw the whole canvas. I'm thinking of switching to a more efficient method though: Put a<svg>
on top of the canvas, and direct all drawing to that: Create the line by using<path>
and save the coordinates passed by the brush in an array. Then, onmouseup
simply remove the<path>
, follow the same coordinates on the canvas usinglineTo
s. – Catastrophe