<!DOCTYPE html> <html> <head> <meta charset="gbk"> </head> <body> <canvas id="c" width="600" height="400"></canvas> <script> var ball = { x: 300, y: 0, r: 15, vx: 0, vy: 0, elasticity: .8 }; var canvas = document.getElementById('c'); var ctx = canvas.getContext('2d'); if (!window.requestAnimationFrame) { window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) { return window.setTimeout(callback, 17 /*~ 1000/60*/); }); } if (!window.cancelRequestAnimationFrame) { window.cancelRequestAnimationFrame = (window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.clearTimeout); } (function drawFrame(){ var raq = requestAnimationFrame(drawFrame,canvas); ctx.save(); ctx.fillStyle = "rgba(0, 0, 0, .3)"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.restore(); ball.x += ball.vx; ball.y += ball.vy; ball.vx *= .99; ball.vy *= .99; ball.vy += .25; if (ball.y + ball.r > canvas.height) { ball.y = canvas.height - ball.r; if (Math.abs(ball.vy) < 1.7) { cancelRequestAnimationFrame(raq); } ball.vy = -Math.abs(ball.vy); ball.vy *= ball.elasticity; } ctx.save(); ctx.translate(ball.x, ball.y); ctx.fillStyle = "#fff"; ctx.beginPath(); ctx.arc(0, 0, ball.r, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.restore(); }()); </script> </body> </html>
运行代码