Amit Shakya
Amit Shakya

Reputation: 994

Create lines in HTML5 Canvas

I need to make path which connected with different colours of lines, but when I assign the last colour the whole path becomes a single colour. lines assignment

My code is

var canvas=document.getElementById("mycanvas");
var ctx=canvas.getContext('2d');

ctx.strokeStyle="#f00";
ctx.lineWidth=5;
ctx.moveTo(100,100);
ctx.lineTo(150,150);
ctx.stroke();
ctx.strokeStyle="#0f0";
ctx.moveTo(150,150);
ctx.lineTo(350,200);
ctx.stroke();
ctx.strokeStyle="#00f";
ctx.moveTo(350,200);
ctx.lineTo(400,400);
ctx.stroke();

Upvotes: 1

Views: 47

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

You must call ctx.beginPath() to begin each canvas path i.e.

var canvas=document.getElementById("mycanvas");
var ctx=canvas.getContext('2d');

ctx.beginPath();
ctx.strokeStyle="#f00";
ctx.lineWidth=5;
ctx.moveTo(100,100);
ctx.lineTo(150,150);
ctx.stroke();

ctx.beginPath();
ctx.strokeStyle="#0f0";
ctx.moveTo(150,150);
ctx.lineTo(350,200);
ctx.stroke();

ctx.beginPath();
ctx.strokeStyle="#00f";
ctx.moveTo(350,200);
ctx.lineTo(400,400);
ctx.stroke();

Upvotes: 2

Related Questions