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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16919862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:04:08  来源:igfitidea点击:

JavaScript waiting until an image is fully loaded before continuing script

javascriptjqueryhtml

提问by Braains

I've been looking around a lot of JavaScript answers but I haven't found one that really answers my problem yet. What I'm trying to do is load an image, grab the pixel data, perform an analysis, and then load another image to repeat the process.

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

My problem is that I can't preload all of the images because this script has to be able to work on large amounts of images and preloading could be too resource heavy. So I'm stuck trying to load a new image each time through a loop, but I'm stuck with a race condition between the image loading and the script drawing it to the canvas's context. At least I'm pretty sure that's what is happening because the script will work fine with the images precached (for example if I refresh after loading the page previously).

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

As you'll see there are several lines of code commented out because I'm incredibly new to JavaScript and they weren't working the way I thought they would, but I didn't want to forget about them if I needed the functionality later.

正如您将看到的,有几行代码被注释掉了,因为我对 JavaScript 非常陌生,而且它们并没有像我想象的那样工作,但是如果我以后需要这些功能,我不想忘记它们.

This is the snippet of code that I believe is giving rise to the problem:

这是我认为导致问题的代码片段:

EDIT: So I got my function to work after following a suggestion

编辑:所以我在遵循建议后让我的功能工作

 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;
}

采纳答案by maximkou

Maybe this will help:

也许这会有所帮助:

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

If it is necessary to wait for the image to load, the following code will load the next image (currentIndex is your "img" variable):

如果需要等待图片加载,下面的代码会加载下一张图片(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++);
    }
}

Instead of a "for" loop, use for example this function:

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

loadImages(imageURLarray);

回答by A. Wolff

Maybe try this:

也许试试这个:

http://jsfiddle.net/jnt9f/

http://jsfiddle.net/jnt9f/

Setting onload handler before setting img src will make sure the onload event be fired even the image is cached

在设置 img src 之前设置 onload 处理程序将确保即使图像被缓存也会触发 onload 事件

var $imgs = $(),i=0;
for (var img = 0; img < imageURLarray.length; img++) {
   $imgs = $imgs.add('<img/>');
}

var fctn = (function fctn(i){
    $imgs.eq(i).on('load',function(){
        //do some stuff
        //...
        fctn(++i);
    }).attr('src',imageURLarray[i]);    
})(0);

回答by klewis

Actually...a lot of developers are pointing here to detect when images are done loading after a jQuery event..

实际上......很多开发人员都指向这里来检测jQuery事件后图像何时完成加载..

https://github.com/desandro/imagesloaded

https://github.com/desandro/imagesloaded

If you can determine when the event triggers your images to load (for example, adding an Id or class onto the page right before your images begin to load), then you should be able to blend that in with this plug-in on github.

如果您可以确定事件何时触发您的图像加载(例如,在您的图像开始加载之前将 Id 或类添加到页面上),那么您应该能够将其与 github 上的此插件混合。

Good Luck!

祝你好运!