Rodrigo
Rodrigo

Reputation: 5129

html5 canvas stroke twice drawing first stroke again

I want to draw a line with one color, and the next line with a different color. But when I call stroke() the second time, the first line is draw again! How can I avoid it? Here's my code:

var canv = document.getElementById("canvas");
var ctx = canv.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.strokeStyle = "#FF0000";
ctx.stroke();
ctx.moveTo(100,100);
ctx.lineTo(100,200);
ctx.strokeStyle = "#999999";
ctx.stroke();

Thanks in advance!

Upvotes: 3

Views: 2852

Answers (1)

user1693593
user1693593

Reputation:

Just insert a beginPath() in there:

var canv = document.getElementById("canvas");
var ctx = canv.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.strokeStyle = "#FF0000";
ctx.stroke();

cxt.beginPath();   // <---
ctx.moveTo(100,100);
ctx.lineTo(100,200);
ctx.strokeStyle = "#999999";
ctx.stroke();

That will reset your path. A stroke just strokes what exists on the path but does not clear it. You will have to manually reset the path for each new shape you want to draw.

The advantage is that you can reuse the path for fill, clip and point testing. The disadvantage is that it's easy to forget sometimes.

Upvotes: 6

Related Questions