如何在背景图像的循环数组中预加载图像
How to preload images during a looped array for background images
我编写了一个简单的循环,它循环遍历数组中的一系列图像,并将其转换为元素的背景图像属性。问题是,由于图像正在加载,所以在最初加载所有内容时,动画会失控。我正在尝试建立一个预加载工作流,其中:
- 通过等待直到第一个图像被完全加载来阻止整个循环
- 每当一个新映像被完全预加载时,它就会开始预加载以下映像
- 当数组结束时,必须停止预加载,并使用缓存的图像,这样在浏览器上就很容易了,而不是永远在图像上加载相同的数组
有什么帮助吗?
http://codepen.io/jeremypbeasley/pen/JoZzyo?editors=001
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
var p = photoSet.length;
console.log(p);
var i = 1;
function loopPhotos() {
setTimeout(function() {
$('div').css({'background-image': 'url(' + photoSet[i] + ')',});
i++;
console.log(i);
// call the next indexed image and begin to preload it
var img = new Image();
img.src = photoSet[i];
if (i >= p) {
i = 0;
// stop preloading images, somehow used images that are cached so the browser isn't working eternally reloading the same X number of photos.
}
loopPhotos();
}, 2000)
}
$(document).ready(function() {
// load first image
var firstImg = new Image();
firstImg.src = photoSet[0];
// when first image is loaded, apply it to background and begin looping
if (firstImg.complete) {
$('div').css({'background-image': 'url(' + firstImg.src + ')',});
loopPhotos();
console.log('first image loaded!');
}
});
这将完成
var photoSet = [
"https://farm6.staticflickr.com/5475/9790841974_182a06590a_o.jpg",
"https://farm3.staticflickr.com/2840/9042399407_bf04388aca_o.jpg",
"https://farm6.staticflickr.com/5504/14634417581_626ea1a835_o.jpg"
];
function preloadImageAndAct(src, action){
var img = new Image();
img.onload = action;
img.src = src;
}
function showImage( src ){
$('div').css({
'background-image': 'url(' + src + ')',
opacity: 1
});
}
var nextImage = 0;
function loopPhotos() {
console.log('Preload and show image #', nextImage);
var nextSrc = photoSet[nextImage];
preloadImageAndAct( nextSrc, function(){
showImage( nextSrc );
setTimeout( function() {
nextImage++;
nextImage %= photoSet.length;
loopPhotos();
}, 2000);
});
}
$(document).ready(function() {
loopPhotos();
});
演示位置http://codepen.io/gpetrioli/pen/rarPay
请记住,不能转换background-image
。如果你想转换图像的变化,你需要使用两个元素或淡出元素/改变src
/淡入元素。
至于缓存,一旦它们被加载,就会被浏览器自动缓存,所以这应该没有问题。
相关文章:
- 使用图像数组列表的simplegallary.js显示适合桌面屏幕的图像
- Javascript图像数组预加载速度和从内存中删除
- 将图像数组访问到动态表中
- Javascript图像数组
- JavaScript 在删除预上传图像时不清除图像数组
- 访问标记图标的图像数组元素
- 使用javascript/jquery获取具有图像数组的对象中的所有图像
- 如何将图像数组应用于Meteor.js中的模板辅助对象
- 如何创建图像数组作为链接
- 循环遍历图像数组并将其显示到HTML页面
- 打乱图像数组jquery
- 来自 flickr 的图像数组未按预期顺序显示
- 将图像数组从一个窗口传递到另一个窗口,并在javascript的新窗口中显示图像
- 使用 javascript 从图像数组中更改 img 标签 src.骰子游戏
- 将图像数组放入表中 - Javascript
- 加载带有 onload 的图像数组,如何限制将它们绘制到画布
- 如何自动循环浏览图像数组
- JavaScript:图像数组
- Javascript图像数组问题
- 在HTML5中使用JavaScript实现图像数组的拖放