Search code examples
javascriptcsscanvasborderstroke

Draw Another Border in line on Canvas


I have problem. I need draw another border in my canvas. If I try this:

c2.beginPath();

c2.moveTo(0, 0);

c2.lineTo(0, 100);
c2.lineWidth = Number(sw) + 6;
c2.strokeStyle = "red";
c2.stroke();
c2.lineTo(100, 100);
c2.lineWidth = Number(sw) + 6;
c2.strokeStyle = "#00ec11";
c2.stroke();
c2.lineTo(0, 100);
c2.lineWidth = Number(ss) + 6;
c2.strokeStyle = "red";
c2.stroke();
c2.closePath();
c2.lineWidth = Number(sw) + 6;
c2.strokeStyle = "#00ec11";
c2.stroke();

c2.fill();

it is not working because all line have green border. Can you help me?

--- Edit: I can;t close patch when close my line bacouse this line draw shape. When i close patch my shape isn't correct. Mayby another ideas?


Solution

  • c2.stroke(); redraws the whole path up to that point with the current strokeStyle. So in the end, only the last style will be applied.

    Try adding c2.closePath(); followed by c2.beginPath() after each c2.stroke() to begin a new path which can have a separate strokeStyle.

    for example:

    c2.lineTo(0, 100);
    c2.lineWidth = Number(sw) + 6;
    c2.strokeStyle = "red";
    c2.stroke();
    c2.closePath();
    
    c2.beginPath();
    c2.moveTo(0, 100);
    c2.lineTo(100, 100);
    c2.lineWidth = Number(sw) + 6;
    c2.strokeStyle = "#00ec11";
    c2.stroke();
    c2.closePath();
    . 
    . 
    .