我已經彈出了爆米花,是的,你可以做到這一點。通過創建一個Image
對象並設置其src
屬性來加載爆米花圖像。使用圖像的onload
屬性來啓動動畫。假設動畫的持續時間爲k,請使用正弦曲線sin(x/(k/π))
來計算每幀顯示的內核數量。
下面是做這件事的一種方式,演示在這裏:http://jsfiddle.net/uyk63/8/
var IMAGE_URL = 'http://i.istockimg.com/file_thumbview_approve/959519/2/stock-photo-959519-isolated-single-popcorn.jpg';
var DURATION = 10 * 1000, FRAMES = 30, KERNELS = 10;
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var frame = 0,
start = new Date().getTime(),
image = new Image;
image.src = IMAGE_URL;
image.onload = function() {
function pop() {
ctx.drawImage(image,
Math.floor(Math.random() * canvas.width),
Math.floor(Math.random() * canvas.height),
100, 50);
}
// A little overcomplicated. You could probably do this in a single loop.
// (It's late and I'm tired, though. Sorry.)
function animate() {
var i, delay,
count = Math.floor(Math.sin(frame/(FRAMES/Math.PI)) * KERNELS);
for (i = 0; i < count; i++) {
delay = (DURATION/FRAMES)/count * i;
setTimeout(pop, delay);
}
if (++frame < FRAMES) {
setTimeout(animate, DURATION/FRAMES);
}
}
animate();
};