1 (function () { 2 3 var img; 4 var canvas = document.getElementById("canvas"); 5 var con = canvas.getContext("2d"); 6 var circleX = 0, circleY = 100, speed = 1; 7 8 function loadImage() { 9 img = new Image(); 10 img.src = "11.jpg"; 11 } 12 13 function render() { 14 circleX += speed; 15 if (circleX > 300) { 16 speed = -1; 17 } 18 if (circleX < 100) { 19 speed = 1; 20 } 21 con.clearRect(0,0,400,300); 22 con.save(); 23 con.beginPath(); 24 con.arc(circleX,circleY,100,0,2*Math.PI); 25 con.closePath(); 26 con.clip(); 27 con.drawImage(img,0,0); 28 con.restore(); 29 30 requestAnimationFrame(render); 31 } 32 33 function init() { 34 loadImage(); 35 render(); 36 } 37 38 init(); 39 })();
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <canvas id="canvas" width="400" height="300"></canvas> 9 <script src="main.js"></script> 10 </body> 11 </html>