JavaScript等待,直到图像完全加载,然后再继续执行脚本

前端之家收集整理的这篇文章主要介绍了JavaScript等待,直到图像完全加载,然后再继续执行脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在寻找很多 JavaScript的答案,但我还没有找到一个真正回答我的问题的答案.我想要做的是加载图像,获取像素数据,执行分析,然后加载另一个图像以重复该过程.

我的问题是,我无法预加载所有的图像,因为这个脚本必须能够处理大量的图像,并且预加载可能太资源沉重.所以我试图加载一个新的图像,每次循环,但我被卡住了一个竞争条件之间的图像加载和脚本绘制到画布的上下文.至少我很确定这是发生了什么,因为脚本可以正常工作正常的图像预先处理(例如,如果我以前加载页面刷新).

你会看到有几行代码注释掉了,因为我对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,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,currentIndex);
  return;
}@H_404_11@

解决方法

也许这将有助于:
currentimage.onload = function(e){
    // code,run after image load
}@H_404_11@ 
 

如果需要等待图像加载,以下代码将加载下一个图像(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++);
    }
}@H_404_11@ 
 

而不是“for”循环,例如使用这个功能

loadImages(imageURLarray);@H_404_11@
原文链接:https://www.f2er.com/js/155100.html

猜你在找的JavaScript相关文章