Restart an animated GIF from JavaScript without reloading the image

╄→гoц情女王★ 提交于 2019-11-26 10:55:51

问题


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.

Here\'s my current code. img and nextimg are <div> tags containing a single <img> each. nextimg_img is the <img> tag corresponding to the next image to be displayed.

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 src attribute of the next image to \'\', then sets it back to the source of the GIF to be displayed.

This works — it restarts the animation from the beginning — but the GIFs seem to be redownloaded every time they are displayed.

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.


回答1:


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.




回答2:


// 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.




回答3:


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.

The only problem is you cannot use the URL of the gif but only its base64.



来源:https://stackoverflow.com/questions/3191922/restart-an-animated-gif-from-javascript-without-reloading-the-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!