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

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

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

你会看到有几行代码被注释掉,因为我对JavaScript非常陌生并且他们没有像我想象的那样工作,但如果我以后需要这些function,我不想忘记他们。

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

编辑:所以我按照建议完成了我的工作

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

也许试试这个:

http://jsfiddle.net/jnt9f/

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

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

实际上……很多开发人员指向这里检测图像是否在jQuery事件之后加载完成。

https://github.com/desandro/imagesloaded

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

祝好运!