gpt4 book ai didi

javascript - 在 html 上快速加载许多图像

转载 作者:搜寻专家 更新时间:2023-11-01 05:14:54 24 4
gpt4 key购买 nike

我正在编写一个脚本,用户可以在其中选择一系列数据,然后我从服务器获取一堆图像(超过 150 张),然后我循环处理它们以制作类似电影的东西。我想知道的是在移动图像时加载防止延迟的最有效方法。

目前我正在使用 Ajax 从服务器获取图像并将它们存储在 JavaScript 上的图像对象数组中。在 HTML 中,我有一个 div 标签,我希望在其中放置图像。在我完成数组中所有 Image 对象的创建(并设置它们的正确 src)后,我执行以下操作:

imgElem = document.createElement('img');
document.getElementById('loopLocation').appendChild(imgElem);
imgElem.src = images[0].src;

在此之后,我只进行了最后一次调用,但更改了循环索引。我每 400 毫秒这样做一次。循环有效,但有时它会滞后并且在图像上卡住的时间比预期的要长。我想知道我是否能够从客户端进一步改进它,或者我只需要一个响应速度更快的服务器。

最佳答案

您可能想考虑 spriting将所有图像放入一个大图像中。有了这个,你只需要加载一个大图像,然后为每个场景重新定位。

或者,您可能还想在实际使用之前预加载这 150 张图像。您可以使用 JS 数组来存储 Image 对象,然后循环遍历该数组以获取您的图像。

var images = [];
var expectLoaded = 150;

for(var i = 0; i<expectLoaded;i++){
(function(i){

//new image object
var img = new Image();

//onload hander
img.onload = function(){

//after load, push it into the array
images.push[img];

//and check if the all has loaded
if(images.length === expectLoaded){
//preload done
}
}

//start loading this image
img.src = //path to image[i];

},(i));
}

循环会阻塞 UI 线程。 JS 是单线程的,这意味着代码以线性方式一个接一个地执行。该循环语句之后的任何内容都将等到循环完成。如果该循环需要很长时间...请喝杯咖啡。另外,由于您正在操作 DOM,因此您看不到更改,因为 UI 线程被阻塞了。

但是有一些方法可以绕过这个,其中之一是使用超时来延迟和排队代码,以便在 JS 不忙时稍后执行。

function animate(frameNo){

//animate frame[frameNo];

if(frameNo < total_frames){ //make the UI breate in between frames
setTimeout(function(){ //so that changes reflect on the screen
animate(++frameNo); //then animate next frame
},200);
}
}

//start
animate(0);

关于javascript - 在 html 上快速加载许多图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9962580/

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