wubbewubbewubbe
wubbewubbewubbe

Reputation: 741

Is it possible to use two different strokestyles on same path in canvas?

Is it possible to create a path in canvas of which the lines are stroked differently? For example so you could draw a box being green on the inside, with 4 different colored edges. I've included some code, but that does not work, because it draws the path twice (first time unfinished path, second time the whole path).

JavaScript

window.onload = function()
{
    canvas = document.getElementById("canvas1");
    if (canvas.getContext)
    {
        ctx = canvas.getContext("2d");
        ctx.beginPath();                
        ctx.save();                
        ctx.moveTo(0, 0);
        ctx.strokeStyle = "rgb(255, 0, 0)";            
        ctx.lineTo(100, 100);
        ctx.stroke();
        ctx.strokeStyle = "rgb(0, 0, 255)";
        ctx.lineTo(200, 100);
        ctx.stroke();                
        ctx.restore();
    }                
}

HTML

<canvas id = "canvas1" width = "400" height = "400">
    Your browser does not support the HTML5 canvas tag.
</canvas>

Upvotes: 1

Views: 248

Answers (1)

Peter Olson
Peter Olson

Reputation: 142921

I think you'll have to use two paths.

    ctx = canvas.getContext("2d");
    ctx.beginPath();                              
    ctx.moveTo(0, 0);          
    ctx.lineTo(100, 100);
    ctx.strokeStyle = "rgb(255, 0, 0)";
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(100, 100);
    ctx.lineTo(200, 100);
    ctx.strokeStyle = "rgb(0, 0, 255)";
    ctx.stroke();

Upvotes: 2

Related Questions