Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Canvas - Different Strokes

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?

like image 787
Kiloku Avatar asked Feb 28 '12 02:02

Kiloku


1 Answers

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.

like image 137
Delta Avatar answered Oct 11 '22 21:10

Delta