一:创建画布
<canvas width="600" height="600" id="canvas"></canvas>
二:代码实现
var canvas = document.getElementById('canvas');
var cxt = canvas.getContext('2d');
var timer;
var gravity = 1;
var buffer = 5;
var iStop = false;
var boxes = [
{'startSpeed':-20,'currentSpeed':-20,'boxTop':500,'boxLeft':0},
{'startSpeed':-10,'currentSpeed':-10,'boxTop':500,'boxLeft':100},
{'startSpeed':-30,'currentSpeed':-30,'boxTop':500,'boxLeft':200},
{'startSpeed':-10,'currentSpeed':-10,'boxTop':500,'boxLeft':300},
{'startSpeed':-20,'currentSpeed':-20,'boxTop':500,'boxLeft':400}
];
function draw(){
for(var i=0; i<boxes.length; i++){
boxes[i].currentSpeed += gravity;
boxes[i].boxTop += boxes[i].currentSpeed;
if(boxes[i].boxTop > 500){
boxes[i].boxTop -= boxes[i].currentSpeed;
}
cxt.fillRect(boxes[i].boxLeft, boxes[i].boxTop, 100, 100);
if(boxes[i].boxTop >= 500){
boxes[i].startSpeed += buffer;
boxes[i].currentSpeed = boxes[i].startSpeed;
}
}
}
function erase(){
cxt.clearRect(0, 0, 600, 600);
}
window.requestAnimationFrame =
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
window.cancelRequestAnimationFrame =
window.cancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame;
function animate() {
erase();
draw();
if(iStop){
cancelRequestAnimationFrame(timer);
}else{
timer = requestAnimationFrame(animate);
}
}
animate();