You can use context.clip
to accomplish clipping an image within a circle
context.clip()
creates a clipping path where any new drawings will only be drawn only inside the defined path. Any drawings that fall outside the clipping path will not show.
Here's how:
Define an circular path.
Create a clipping path from the circular path.
Draw the image and it will be clipped within the circular clipping region.
Illustrating code:
// define a path
context.beginPath();
context.arc(100,100,75,0,Math.PI*2);
context.closePath();
context.stroke(); // the stroke is optional
// clip new drawings within this path
context.clip();
// draw the image
// Note: adjust the x,y of drawImage to "frame" your image as desired
context.drawImage(anyImageObject,100-75,100-75);
Here's an example of an image clipped inside an animated circle:
http://jsfiddle.net/m1erickson/255JU/
Example code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// ball related variables
var x=50;
var y=100;
directionX=3;
directionY=2;
var radius=32;
var offsetX=-37;
var offsetY=-34;
var angle=0;
// the image to be clipped inside the ball
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png";
function start(){
// start the animation
animate();
}
function drawBall(x,y,radius,img,imgOffsetX,imgOffsetY,radianAngle){
// create a stroked circle at x,y and rotated by radianAngle
ctx.save();
ctx.beginPath();
ctx.translate(x,y);
ctx.rotate(radianAngle);
ctx.arc(0,0,radius,0,Math.PI*2);
ctx.closePath();
ctx.stroke();
// make the circle a clipping region
ctx.clip();
// draw the image into the clipping region
// (only part of the image will show--the part inside the circle
ctx.drawImage(img,imgOffsetX,imgOffsetY);
// restore the context to its original untranslated/unrotated state
ctx.restore();
}
function animate(){
// request another animation frame
requestAnimationFrame(animate);
// clear the canvas
ctx.clearRect(0,0,canvas.width,canvas.height);
// draw the ball
drawBall(x,y,radius,img,offsetX,offsetY,angle);
// increment the x,y position of the ball
x+=directionX;
if(x<radius || x>canvas.width-radius){directionX*=-1; x+=directionX;}
y+=directionY;
if(y<radius || y>canvas.height-radius){directionY*=-1; y+=directionY;}
// increment the angle of the ball
angle+=Math.PI/90;
}
}); // end $(function(){});
</script>
</head>
<body>
<p>Animated ball with image clipped inside</p>
<canvas id="canvas" width=300 height=300></canvas>
<p>The original image is below</p>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png">
</body>
</html>