我有 25 张图像想要快速显示,有点像没有效果的幻灯片。我的图像被命名为 0 到 26。
我尝试设置一个 for 循环和一个 setTimeout 来延迟,但 setTimeout 仅在 for 循环结束时运行,在我的检查点显示 i = 25。
JS:
function startAnimation(){
for(var i=0; i<25; i++){
setTimeout(function(){
img = new Image();
img.src = 'images/canvas/'+[i]+'.jpg';
img.onload = function(){ctx.drawImage(img,0,0, 850,194)}
alert('CP. In setTimeout. i= '+i);
},1000);
ctx.clearRect(0,0,canvas.width, canvas.height); //clear image after 1 sec, loop to show next.
alert('CP outside. i = '+i);
}
}
我遵循了这个解决方案How do I add a delay in a JavaScript loop? :
function startAnimation(){
setTimeout(function(){
img = new Image();
img.src = 'images/canvas/'+[counter]+'.jpg';
img.onload = function(){ctx.drawImage(img,0,0, canvas.width,canvas.height)};
counter++;
if(counter<26){
startAnimation();
}
},150)
}
它似乎按照我想要的方式工作。
最佳答案
//preload your images into an array first for smoother animation
function getImages(callback) {
var imgs = [],
loaded = 0,
length = 25,
i;
for (i = 0; i < length; i++) {
(function (i) {
//create image
var img = new Image();
//set a callbacl
img.onload = function () {
//add to array
imgs[i] = img;
//increment loaded count
loaded++;
//if we loaded all of them, call the callback passing in the images
if (loaded === length) callback(imgs);
}
//load
img.src = 'images/canvas/' + [i] + '.jpg';
}(i));
}
}
function startAnimation(i) {
//get all images
getImages(function (imgs) {
var i = 0;
//run through ueach in an interval
var animationInterval = setInterval(function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (i < imgs.length) {
ctx.drawImage(img[i++], 0, 0, 850, 194)
} else {
clearInterval(animationInterval);
}
}, 1000);
});
}
//call
startAnimation();
关于javascript - 尝试在 Canvas 中延迟循环播放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824480/