<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>探照灯的简单效果</title> </head> <body> <canvas id="canvas" width="500" height="500"></canvas> </body> <script type="text/javascript"> var context = canvas.getContext('2d'); //准备这个对象 //创建显示区域的构造函数 function Ball(x, y, r, color, speedX, speedY) { this.x = x; this.y = y; this.r = r; this.color = color; this.speedX = speedX; this.speedY = speedY; this.draw = function() { context.arc(this.x, this.y, this.r, 0, Math.PI * 2); context.fillStyle = this.color; context.fill(); } this.move = function() { this.x = this.speedX + this.x; //让显示区域不要出边界 if((this.x - this.r <= 0) || (this.x + this.r > canvas.width)) { this.speedX = this.speedX * (-1); } this.y = this.speedY + this.y; if((this.y - this.r <= 0) || (this.y + this.r > canvas.height)) { this.speedY = this.speedY * (-1); } } } var img = new Image(); img.src ='img/1.jpg'; img.onload = function(){ context.drawImage(img, 0, 0, canvas.width, canvas.height); } var ball = new Ball(100, 100, 60, 'red', 5, 3); function animation (){ context.clearRect(0, 0, canvas.width, canvas.height); context.save(); context.beginPath(); ball.move(); ball.draw(); //这个和计时器一样的效果 requestAnimationFrame(animation); //将图片进行剪切 context.clip(); context.drawImage(img, 0, 0, canvas.width, canvas.height); //将画布进行恢复 context.restore(); } animation(); </script> </html>
初学canvas 的练练手不错 简单的模拟下探照灯的效果