HTML5 Canvas drawing multicolored lines

23,365

Call ctx.beginPath before drawing each line. When the strong stroke call is made, the first line is still part of the current path so it gets drawn again in the new color.

Share:
23,365
Amarsh
Author by

Amarsh

Updated on July 18, 2020

Comments

  • Amarsh
    Amarsh almost 4 years

    I am trying to draw two parallel lines on the canvas, but it seems like properties of the latter overwrites the former. Please suggest what could be wrong :

    <html>
    <head>
    <script type="application/javascript">
      function draw() {
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        // draw a 10 pix green line
        ctx.strokeStyle='#00cc00';
        ctx.lineWidth=10;
        ctx.moveTo(100,0);
        ctx.lineTo(100,1000);
        ctx.stroke();
        // draw a 20 pix red line
        ctx.strokeStyle='#cc0000';
        ctx.lineWidth=20;
        ctx.moveTo(140,0);
        ctx.lineTo(140,1000);
        ctx.stroke();
      }
      </script>
      </head>
      <body onload="draw()">
        <div><canvas id="canvas" width="1000" height="1000"></canvas></div>
      </body>
      </html>
    
  • Auh
    Auh over 3 years
    Is there a more efficient way to draw a lot of multi-coloured lines? I'm drawing about 5000 per frame and if I make it all a single path I can run it at easy 50fps. But if I make each one an individual path so I can recolour them as I want, it chugs to 15fps. (Do you think this deserves it's own question maybe?)
  • Matti Virkkunen
    Matti Virkkunen over 3 years
    @Auh Have you tried batching together lines of the same color into the same path?
  • Auh
    Auh over 3 years
    Actually, after some testing I found that that if i dont have any shadowBlur on the lines, it runs perfectly fine. Now I have a different issue on my hands.