gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 12:26:00 26 4
gpt4 key购买 nike

我一直在寻找大量的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com