9

I have to draw a graph with 3 different lines. A line graph.

I tried doing this:

function draw() 
{  
    var canvas = document.getElementById("canvas");  
    var ctx = canvas.getContext("2d");      
    ctx.lineWidth=10;

    ctx.strokeStyle="teal";
    ctx.moveTo(10,CompanyA[0]);
    ctx.lineTo(110,CompanyA[1]);
    ctx.lineTo(210,CompanyA[2]);
    ctx.stroke();


    ctx.strokeStyle="green";
    ctx.moveTo(10,CompanyB[0]);
    ctx.lineTo(110,CompanyB[1]);
    ctx.lineTo(210,CompanyB[2]);
    ctx.stroke();       

    ctx.strokeStyle="yellow";
    ctx.moveTo(10,CompanyC[0]);
    ctx.lineTo(110,CompanyC[1]);
    ctx.lineTo(210,CompanyC[2]);
    ctx.stroke();
}

But apparently, the last stroke draws for all the lines. So I get 3 yellow lines, instead of a Teal, a Green and a Yellow one. I tried creating three different Context (ctx1, ctx2 and ctx3), but for some reason, all were drawn with the "ctx3.stroke()" call.

What would be the correct way to do this?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Kiloku
  • 474
  • 3
  • 7
  • 14

2 Answers2

23

Add a ctx.beginPath() call before every line, and also a ctx.closePath() after every ctx.stroke()

If you don't, every time you call the stroke() method, not only the new line will be drawn but also all the previous lines will be drawn again (with the new strokeStyle), since it's the same line path that is still open.

Delta
  • 4,098
  • 2
  • 26
  • 36
  • 2
    This is correct, but just to add some explanation: You have assembled a path of three segments, stroking the first part in teal, then the first and second parts in green, then all three parts in yellow. The yellow is drawing over the others. – Russell Zahniser Feb 28 '12 at 02:22
  • Hey, thanks Russell Zahniser, I have added an explanation to my answer. – Delta Feb 28 '12 at 02:24
  • Good explanation At http://html5tutorial.com/advanced-path-painting you can find a deep study on this issue. – Alex May 18 '12 at 09:16
  • 1
    ctx.closePath is useless, it's just a lineTo previous starting point, it doesn't end a path declaration. – Kaiido Oct 07 '17 at 14:30
  • closePath() is for closing off a previously drawn path where a line is added from the current point to the start point of the first line. This answer correctly states that beginPath() is required for each new path drawn but the closePath() call is redundant. – the_new_mr Apr 15 '21 at 02:00
1

Although there is a functional answer here, I'd just like to add this.

var ctx1 = canvas.getContext("2d");
var ctx2 = canvas.getContext("2d");
var ctx3 = canvas.getContext("2d");

They all refer to the same object. It does not create a new context, it uses the one that's already attached to the canvas element. Delta is totally right in saying that it strokes yellow over the entire path because you did not begin a new path. ctx.beginPath() will solve your troubles.

RoboticRenaissance
  • 845
  • 1
  • 10
  • 15