Cut out circular image in canvas

8k views Asked by At

I am useing html5 canvas, and I am creating a game were it is going to be possible to upload your face into the game, and use it as the main charactar. Unfortunately, the charactars in the game are circular, like smiley faces.

So how would this be done?

Is it possible to take a picture, and cut a circle out of it, so anything outside the circle would be transparent? If so, how would this be done?

1

There are 1 answers

0
Simon Sarris On

You'll want to make a clipping path. This path will clip everything outside of a circle:

ctx.save();

ctx.beginPath();
ctx.arc(75, 75, 10, 0, Math.PI*2, true); 
ctx.closePath();
ctx.clip();

// draw the image

ctx.restore();

So the next thing(s) you draw on this canvas will only appear inside of the clipping path.

You'll want to save and restore the context before and afterwards.

Here's a bit more on the topic:

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing#Clipping_paths