JavaScript 在继续脚本之前等待图像完全加载

标签 javascript jquery html

我一直在寻找大量的 JavaScript 答案,但我还没有找到真正解决我的问题的答案。我想要做的是加载图像、获取像素数据、执行分析,然后加载另一幅图像以重复该过程。

我的问题是我无法预加载所有图像,因为此脚本必须能够处理大量图像并且预加载可能占用大量资源。所以我每次都试图通过一个循环加载一个新图像,但我在图像加载和脚本将它绘制到 Canvas 的上下文之间遇到了竞争条件。至少我很确定这就是正在发生的事情,因为脚本可以很好地处理预缓存的图像(例如,如果我在之前加载页面后刷新)。

正如您将看到的,有几行代码被注释掉了,因为我对 JavaScript 非常陌生,它们并没有按照我想象的方式工作,但如果我需要的话,我不想忘记它们稍后的功能。

我认为这是引起问题的代码片段:

编辑:所以我在听从建议后让我的功能开始工作

 function myFunction(imageURLarray) {
  var canvas = document.getElementById('imagecanvas');
  console.log("Canvas Grabbed");

  if (!canvas || !canvas.getContext) {
    return;
  }

  var context = canvas.getContext('2d');

  if (!context || !context.putImageData) {
    return;
  }

  window.loadedImageCount = 0;
  loadImages(context, canvas.width, canvas.height, imageURLarray, 0);
}

function loadImages(context, width, height, imageURLarray, currentIndex) {
  if (imageURLarray.length == 0 || imageURLarray.length == currentIndex) {
    return false;
  }
  if (typeof currentIndex == 'undefined') {
    currentIndex = 0;
  }

  var currentimage = new Image();
  currentimage.src = imageURLarray[currentIndex];

  var tempindex = currentIndex;
  currentimage.onload = function(e) {

    // Function code here

    window.loadedImageCount++;

    if (loadedImageCount == imageURLarray.length) {

      // Function that happens after all images are loaded here
    }
  }
  currentIndex++;
  loadImages(context, width, height, imageURLarray, currentIndex);
  return;
}

最佳答案

也许这会有所帮助:

currentimage.onload = function(e){
    // code, run after image load
}

如果需要等待图片加载,下面的代码会加载下一张图片(currentIndex是你的“img”变量):

var loadImages = function(imageURLarray, currentIndex){
    if (imageURLarray.length == 0 || imageURLarray.length == currentIndex) return false;
    if (typeof currentIndex == 'undefined'){
       currentIndex = 0;
    }
    // your top code
    currentimage.onload = function(e){
        // code, run after image load
        loadImages(imageURLArray, currentIndex++);
    }
}

代替“for”循环,例如使用这个函数:

loadImages(imageURLarray);

关于JavaScript 在继续脚本之前等待图像完全加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16919862/

相关文章:

javascript - 使用 View 在 couchDB 中的文档之间返回唯一值

javascript - 原型(prototype)到 jQuery : Mindset migration?

php - jQuery 等待服务器响应超时

javascript - 检索不正确的表坐标

css - 填充底部不起作用。我在 chrome 浏览器中测试

javascript - 如何将表头添加到使用 jQuery 中的 getJSON() 函数创建的 html 表

javascript - 将 window.document 样式应用于 Polymer 2 子元素

javascript - AngularJS: Controller 中的函数被模板多次调用

javascript - Html2canvas 拍摄高品质屏幕截图 "SCALE"

jquery - 单击链接打开日期选择器