我正在學習Javascript和canvas動畫。試圖用動畫做一些事情來提升我的技能,這次它是一款簡單的老虎機。AnimationFrame動畫速度如此之慢的原因是什麼?
如果有人能解釋我爲什麼這臺「機器」如此緩慢,這將是偉大的?我做錯了什麼?
我想使用requestAnimationFrame而不是SetInterval。
而最後,對於你somebodie的是我的代碼可能是可怕的,但請記住,我只是學習:)
function main(){ // This is the main function
canvas = document.createElement('canvas');
canvas.width = WIDTH;
canvas.height = HEIGTH;
ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
init();
canvas.addEventListener('click', function(){
// update();
// window.requestAnimationFrame(update);
// setInterval(update, 100);
update();
});
};
main();
function imgLoad(imgArray){
var Images = [];
imgArray.forEach(function(link){
img = new Image();
img.src = link;
Images.push(img);
});
return Images;
};
function Reel(x ,y){ // This is my constructor with drawImage method
var _this = this;
_this.x = x;
_this.y = y;
_this.vel = 5;
_this.counter = 20;
this.changeY = function(){
_this.y += _this.vel;
};
this.draw = function(){ // this function draws rows with images
imgLoad(imgArray);
img.addEventListener('load', function(){
for(var i = 0; i < imgLoad(imgArray).length; i+=1){
ctx.drawImage(imgLoad(imgArray)[i], _this.x, _this.y + i * canvas.height/4, canvas.width/5, canvas.height/4);
}
});
};
function makeReels(){ // making the instances of Reel constructor
for(var i = 0; i < 5; i+=1){
reels.push(new Reel(canvas.width/5 * i, 0));
}
};
function init(){ // drawing first images
makeReels();
for(var i = 0; i < 5; i+=1){
reels[i].draw();
};
};
function update(){ // this is my update function the I'm redrawing images with new Y position
for(var i = 0; i < 5; i+=1){
(function(i){
setTimeout(function(){
ctx.clearRect(0,0,canvas.width,canvas.height);
reels[i].changeY();
reels[i].draw();
}, 100 * i);
})(i);
};
reels[0].counter --;
if(reels[0].counter > 0){
window.requestAnimationFrame(update);
}
else {
window.cancelAnimationFrame(update);
reels[0].counter = 20;
}
};
慢是很模糊的,你能提供一個工作的例子嗎? – vitr
@DarthJS我建議你花些時間閱讀這個http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/我用它,並沒有動畫問題。 – rottenoats
@vitr是的,我知道。我試圖把它放入Jsfiddle,但它不起作用 [JSFiddle鏈接](http://jsfiddle.net/Ldso8sac/) – DarthJS