canvas 实现掉落效果

var canvas = document.getElementById('canvas');
var cxt = canvas.getContext('2d');

cxt.strokeStyle = 'red';

var gravity = 0.98;
var timer;
var index = 0;
var end = 550;
var iStop = false;

var blocks = [
{'left':0,'top':0,'end':0,'speed':0,'startIndex':0},
{'left':50,'top':0,'end':0,'speed':0,'startIndex':10},
{'left':100,'top':0,'end':0,'speed':0,'startIndex':20},
{'left':150,'top':0,'end':0,'speed':0,'startIndex':30},
{'left':200,'top':0,'end':0,'speed':0,'startIndex':40},
{'left':250,'top':0,'end':0,'speed':0,'startIndex':50},
{'left':300,'top':0,'end':0,'speed':0,'startIndex':60},
{'left':350,'top':0,'end':0,'speed':0,'startIndex':70},
{'left':400,'top':0,'end':0,'speed':0,'startIndex':80},
{'left':450,'top':0,'end':0,'speed':0,'startIndex':90},
{'left':500,'top':0,'end':0,'speed':0,'startIndex':100},
{'left':550,'top':0,'end':0,'speed':0,'startIndex':110}
];

function erase() {
cxt.clearRect(0, 0, canvas.width, canvas.height)
}

function draw() {
for(var i=0; i<blocks.length; i++){
if(blocks[i].startIndex <= index){
cxt.fillRect(blocks[i].left, blocks[i].top, 50, 50);
cxt.strokeRect(blocks[i].left, blocks[i].top, 50, 50);
if(blocks[i].top >= end){
blocks[i].top = end;
}else{
blocks[i].top += blocks[i].speed;
blocks[i].speed += gravity;
}
}
}
}

function animate() {
erase();
draw();
index ++;
if(iStop){
cancelRequestAnimationFrame(timer);
}else{
timer = requestAnimationFrame(animate);
}
}

animate();

原文地址:https://www.cnblogs.com/liubu/p/7846964.html