javascript - 尝试在 Canvas 中延迟循环播放图像

标签 javascript html arrays loops delay

我有 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/

相关文章:

javascript - 如何使用 jQuery .each() 获取数据属性

c - C 中结构体的三维数组

arrays - 优化 3D 阵列上的函数速度

c++ - 我可以在我的代码中更改什么以使我的 Quicksort 功能正常工作? (使用结构和数组对姓氏进行排序)

javascript - 输入和下拉有不同的值

javascript - 如何在每次单击按钮时增加/减少视口(viewport)元值(初始比例、最大比例或最小比例)?

javascript - 有人能解释一下为什么 "operator precedence"适用于 javaScript 中的 "||"、 "&&"等逻辑运算符吗

javascript - 居中动态宽度 Divs

javascript - 检测是否支持&lt;input type ="file"/>

javascript - 当我点击离开时隐藏 DIV