![](/img/trans.png)
[英]How to add a ball over the line and move the ball with each click in HTML5?
[英]How to add an image in HTML5 Ball Pool
您可以使用context.clip
在一個圓圈內完成圖像的裁剪
context.clip()
創建一個剪切路徑,在該剪切路徑中,僅在定義的路徑內才繪制任何新圖形。 不在剪切路徑之外的任何圖形都不會顯示。
這是如何做:
定義一個圓形路徑。
從圓形路徑創建剪切路徑。
繪制圖像,它將被剪切在圓形剪切區域內。
說明代碼:
// 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);
這是一個在動畫圓中裁剪的圖像的示例:
http://jsfiddle.net/m1erickson/255JU/
示例代碼:
<!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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.