HTML5 Canvas - Various Strokes

I need to draw a graph with three different lines. Line graph.

I tried to do 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 final touch draws for all lines. Thus, I get 3 yellow lines, instead of teak, green and yellow. I tried to create three different contexts (ctx1, ctx2 and ctx3), but for some reason they were all drawn using the call to "ctx3.stroke ()".

What would be the right way to do this?

+6
source share
2 answers

Add a call to ctx.beginPath() before each line, as well as ctx.closePath() after each ctx.stroke()

If you do not, every time you call the stroke() method, not only a new line will be drawn, but all previous lines will be drawn again (with a new Style stroke), since this is the same line path that is still open.

+20
source

Although there is a functional answer here, I just wanted 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 is already attached to the canvas element. Delta is absolutely right in saying that she strokes all the way, because you have not started a new path. ctx.beginPath() will solve your problems.

0
source

Source: https://habr.com/ru/post/909508/


All Articles