我想制作一个由多个在网页中加载的gif图像组装而成的动画。
因此,我将把一个gif放在另一个gif上面来实现这个效果。 为了使它正常工作,gif必须同时加载。 在Web编程中如何实现这一点?
我想制作一个由多个在网页中加载的gif图像组装而成的动画。
因此,我将把一个gif放在另一个gif上面来实现这个效果。 为了使它正常工作,gif必须同时加载。 在Web编程中如何实现这一点?
这些gif图需要同时加载。
有一种叫做CSS雪碧图的技术。
不是加载4个100x100像素的GIF(或PNG)文件,而是加载一个200x200像素的GIF文件并在一系列100x100像素的div中,重新定位background-image
,以仅显示您要显示的200x200像素图像的部分:
.box {
float: left;
width: 100px;
height: 100px;
margin: 6px 12px 6px 0;
background-image: url(http://placehold.it/200x200);
}
.top-left {
background-position: 0 0;
}
.top-right {
background-position: -100px 0;
}
.bottom-left {
background-position: 0 -100px;
}
.bottom-right {
background-position: -100px -100px;
}
.original {
clear: left;
width: 200px;
height: 200px;
}
<div class="box top-left"></div>
<div class="box top-right"></div>
<div class="box bottom-left"></div>
<div class="box bottom-right"></div>
<div class="box original"></div>
每个GIF都使用以下方式进行加载:
gif = new Image();
gif.src = 'image url';
gif.onload = handleLoading();
而 handleLoading()
函数会在所有 Gif 触发它们的 onload
事件后立即触发 startAnimation()
函数:
function handleLoading()
{
// numLoadedGifs is a counter previously initialized as zero
// gifUrls is an array of the urls to load
numLoadedGifs++;
if (numLoadedGifs === gifUrls.length)
{
// now all images are completely loaded
startAnimation();
}
};
接下来,startAnimation()
函数将之前创建的 img
元素(存储在一个数组中)作为子元素添加到 <div id="animation">
中,但为了让它们同时运行,需要重置并重新设置它们的 src
属性:
function startAnimation()
{
var animationDiv = document.getElementById('animation');
for (var index in gifList)
{
var img = animationDiv.appendChild(gifList[index]);
img.classList.add('cloth');
img.src = '';
img.src = gifUrls[index];
}
};
src
是使其在IE 11中正常工作的原因)。
src
,因此https://jsfiddle.net/baz3ynt1/10/将这两个任务分开。function startAnimation()
{
var animationDiv = document.getElementById('animation');
for (var index in gifList)
{
var img = animationDiv.appendChild(gifList[index]);
img.classList.add('cloth');
}
for (var index in gifUrls)
{
gifList[index].src = '';
gifList[index].src = gifUrls[index];
}
};