gpt4 book ai didi

javascript - 停止$.each,加载图像然后继续循环

转载 作者:行者123 更新时间:2023-12-02 17:07:34 27 4
gpt4 key购买 nike

我需要停止 $.each 循环,加载图像,然后继续循环。我有 Canvas ,可以在其中加载对象图像。对象以正确的顺序排列在数组中。现在,当我尝试从数组加载对象时,存在一个问题:由于尺寸不同,并且它们在 Canvas 上绘制,因此图像加载速度变慢或变快。以相反的顺序。我希望你能理解我,因为我的英语不太好。无论如何,祝你好运:)

    $.each(content,function(i){
obj_id[i] = $.inArray( content[i], different_objects ) != -1 ? time == "day" ? content[i] + 'd' : content[i] : content[i];
temp[i] = new Image();
temp[i].src = '../data/img/objects/' + obj_id[i] + '.png?' + i;
$(temp[i]).on('load', function() {
city_cvs.drawImage({
layer: true,
source: '../data/img/objects/' + obj_id[i] + '.png?' + i,
x: offset + x + content_pause, y: y - temp[i].height,
fromCenter: false,
opacity: opacity
});

offset = offset + temp[i].width + content_pause;
});
});

最佳答案

我建议您开始加载所有图像(以获得最佳性能),然后添加一些逻辑以确保在它们到达时按顺序绘制它们 - 绘制尽可能多的尚未在每个图像上绘制的连续图像加载事件。操作方法如下:

var images = [];
var lastDrawn = -1;
$.each(content,function(i){
obj_id[i] = $.inArray( content[i], different_objects ) != -1 ? time == "day" ? content[i] + 'd' : content[i] : content[i];
var img = new Image();
// put empty image slot in the array
images[i] = null;
img.onload = function() {
// mark this one as loaded now
images[i] = this;
// now draw all sequential images since lastDrawn that are ready
// code will stop drawing when it encounters an image that is not yet ready
for (var imageIndex = lastDrawn + 1; imageIndex < images.length; imageindex++) {
// if the image in this slot is ready, draw it
if (images[imageIndex]) {
city_cvs.drawImage({
layer: true,
source: images[imageIndex].src,
x: offset + x + content_pause, y: y - images[imageIndex].height,
fromCenter: false,
opacity: opacity
});
// update the lastDrawn index
lastDrawn = imageIndex;
} else {
// found an image that is not yet ready so stop drawing for now
break;
}
}
}
// must set .src property AFTER the onload handler is set (IE will fire onload immediately if the image is cached
img.src = '../data/img/objects/' + obj_id[i] + '.png?' + i;
});

关于javascript - 停止$.each,加载图像然后继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109609/

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