[whatwg] Canvas stroke alignment

David Flanagan david at davidflanagan.com
Tue Jul 20 10:36:02 PDT 2010


Nick wrote:
> Canvas would benefit from a way to set stroke alignment. With the only 
> available alignment being center, which is not very useful, custom paths 
> have to be drawn to mimic inside and outside stroke alignment. That 
> workaround may give unwanted transparency on pixels between a path and 
> its stroke path once a path goes diagonal or curves.
> 
> Having Canvas take care of stroke alignment (center, inside and outside) 
> by adding something like strokeAlign can fix these transparency problems 
> and makes adding strokes a lot easier and more useful.
> 
> -- 
> Nick Stakenburg
> 

Currently for inside alignment, I think you can do this, with no 
computation of custom path:

c.save();
c.clip();
c.lineWidth *= 2;
c.stroke();
c.restore();

Outside alignment is easy if you're also going to fill the path, of 
course.  But if you want to leave the inside of the path untouched you 
could do something like this, I think:

var url = canvas.toDataURL();  // Back up canvas content
var img = document.createElement("img");
img.src = url;
c.save();
c.linewidth *= 2;
c.stroke();
c.clip();
c.drawImage(img, 0, 0);  // Restore original bitmap inside the path
c.restore();

You can't use getImageData()/putImageData() for this, since they ignore 
the clipping region.

Another approach for outside stroke alignment, if you know the 
directionality of your path would be to turn the path inside out by 
drawing an off-screen rectangle around the canvas in the opposite 
direction.  Then the outside of your path becomes the inside of the new 
path and you can use the technique above for inside alignment...

	David



More information about the whatwg mailing list