Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut out circular image in canvas

Tags:

html

canvas

blit

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?

like image 886
MrJuavo Avatar asked Feb 02 '11 14:02

MrJuavo


Video Answer


1 Answers

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

like image 178
Simon Sarris Avatar answered Sep 18 '22 19:09

Simon Sarris