Posted by & filed under Coding.

I had an interesting clipping problem for the HTML5 Canvas tag. I wanted a donut clipping. For example, I had a circle like this:

cvs_circle

And I wanted the center to show through like so:

cvs_donut

My first pass looked something like this:

 

function testclip() {
	var cvs = document.getElementById('cvs');
	var ctx = cvs.getContext('2d');
	ctx.beginPath();
	ctx.arc(50,50,40,0,Math.PI*2,false);
	ctx.arc(50,50,20,0,Math.PI*2,false);
	ctx.clip();
	ctx.fillStyle = 'white';
	ctx.beginPath();
	ctx.rect( 0, 0, 100, 100 );
	ctx.fill();
}

 

Turns out that the inner circle is a no-op because of the direction of the clip assembly. If you draw the inner circle in the other direction, like so:

 

	ctx.arc(50,50,20,0,Math.PI*2,true);

 

Note the true at the end instead of the false. In that case you get the nice donut shaped clipping region.

Leave a Reply

  • (will not be published)