在不重新加载图像的情况下从 JavaScript 重新启动动画 GIF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3191922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restart an animated GIF from JavaScript without reloading the image
提问by nornagon
I am creating a slideshow of animations using animated GIFs. I'm crossfading from one animation to the next. The problem is: the only way I have discovered to ensure that the GIF starts animating from the first frame is to reload it each time it's shown. The GIFs are 200KB or so each, which is way too much bandwidth for a continuous slideshow.
我正在使用动画 GIF 创建动画幻灯片。我正在从一个动画到下一个动画淡入淡出。问题是:我发现确保 GIF 从第一帧开始动画的唯一方法是每次显示时重新加载它。每个 GIF 大约 200KB,这对于连续幻灯片放映来说是太多的带宽。
Here's my current code. imgand nextimgare <div>tags containing a single <img>each. nextimg_imgis the <img>tag corresponding to the next image to be displayed.
这是我当前的代码。img和nextimg是<div>包含单个<img>每个的标签。nextimg_img是<img>下一张要显示的图片对应的标签。
var tmp = nextimg_img.attr('src');
nextimg_img.attr('src', '');
setTimeout(function() { nextimg_img.attr('src', tmp); }, 0);
img.fadeOut('slow');
nextimg.fadeIn('slow');
The idea is that it sets the srcattribute of the next image to '', then sets it back to the source of the GIF to be displayed.
这个想法是它将src下一个图像的属性设置为'',然后将其设置回要显示的 GIF 的源。
This works — it restarts the animation from the beginning — but the GIFs seem to be redownloaded every time they are displayed.
这有效——它从头开始重新启动动画——但每次显示 GIF 时似乎都会重新下载它们。
EDIT: it's a looping slideshow, and I'm trying to avoid reloading the GIFs from the net when they get shown the second/third/subsequent time.
编辑:这是一个循环幻灯片,我试图避免在第二次/第三次/后续时间显示时从网上重新加载 GIF。
回答by spinon
You should preload your images into code.
您应该将图像预加载到代码中。
var image = new Image();
image.src = "path";
when you want to use:
当你想使用:
nextimg_img.attr('src', image.src);
Then when you swap the src out just swap from the preloaded image objects. That should do the trick to avoid redownloading.
然后,当您交换 src 时,只需从预加载的图像对象中交换即可。这应该可以避免重新下载。
回答by Alvaro Joao
// reset a gif in javascript
img.src = "your_image_url.gif"+"?a="+Math.random();
Tada!
多田!
Please note the GIF will be downloaded every time so keep it a small file.
请注意,每次都会下载 GIF,因此请将其保存为一个小文件。
回答by wizawu
I just solved it. Place this code (or another static image if you like) on the page first:
我刚刚解决了。首先将此代码(或其他静态图像,如果您喜欢)放在页面上:
<img src="data:image/gif;base64,">
Then replace it with the following code when you are ready to play it:
然后在准备播放时将其替换为以下代码:
<img src="data:image/gif;base64,R0lGODl...AH0AvI">
It will play from the beginning of the gif.
它将从 gif 的开头播放。
The only problem is you cannot use the URL of the gif but only its base64.
唯一的问题是您不能使用 gif 的 URL,而只能使用它的 base64。

