mbq
mbq

Reputation: 18628

Converting stroke to path in HTML canvas

Can I stroke a path so that it is not drawn on screen but converted to a new path? If so, how?

Upvotes: 1

Views: 1320

Answers (1)

Simon Sarris
Simon Sarris

Reputation: 63812

In canvas, (almost) all shapes, stroked or filled, are paths. There is no concept of a "stroke" in canvas, but there is the concept of calling stroke() on a path.

What you can do is create a path, fill it, and then stroke the very same path.

ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(100,100);
ctx.lineTo(25,100);
ctx.closePath();


ctx.fillStyle = 'gold'
ctx.fill();

// The path is still there, lets stroke it
ctx.lineWidth = 4;
ctx.stroke();

Live example:

http://jsfiddle.net/9SK2C/

However note that once you start a new path, that old path is lost forever. There is no built in way to save or restore paths. If you want to keep track of a path to save/restore it, you have to account for it all yourself.

You also cannot edit a path. You can add it the end of it, but there's no going back and modifying the points in a path like there is in (say) SVG. You gotta remake it from the start with the new points instead.

Upvotes: 4

Related Questions