I have the following code to "freeze" a gif within 5 seconds, however the gif stops as soon as the window.onLoad event is fired:
[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);
function is_gif_image(i) {
return /^(?!data:).*\.gif/i.test(i.src);
}
function freeze_gif(i) {
var c = document.createElement('canvas');
var w = c.width = i.width;
var h = c.height = i.height;
c.getContext('2d').drawImage(i, 0, 0, w, h);
try {
i.src = c.toDataURL("image/gif");
} catch(e) {
for (var j = 0, a; a = i.attributes[j]; j++)
c.setAttribute(a.name, a.value);
i.parentNode.replaceChild(c, i);
}
}
window.onLoad = function(){
var gifs = freeze_gif(i);
setTimeout( function() {
gifs[n].click();
}, 5000);
}
Is it correct to include the setTimeout in window.onLoad? I have tried to include it in the freeze_gif(i), but the gif keeps stopping when the event is fired up. Can you help?
Thank you
EDIT 1: As rightly recommended, I am including a working example of the current code:
You are running this line at start:
[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);
And it freezing all of your images.
The problem with jsfiddle is that all the javascript code there is already inside window.load
so you can't really use it twice, but here is the same inside snippet:
function is_gif_image(i) {
return /^(?!data:).*\.gif/i.test(i.src);
}
function freeze_gif(i) {
var c = document.createElement('canvas');
var w = c.width = i.width;
var h = c.height = i.height;
c.getContext('2d').drawImage(i, 0, 0, w, h);
try {
i.src = c.toDataURL("image/gif");
} catch(e) {
for (var j = 0, a; a = i.attributes[j]; j++)
c.setAttribute(a.name, a.value);
i.parentNode.replaceChild(c, i);
}
}
window.onload = function() {
setTimeout(function() {
[].slice.apply(document.images).filter(is_gif_image).map(freeze_gif);
}, 5000);
}
<img src="http://rubentd.com/img/banana.gif" alt="" >
I moved the first line (that cases the freeze of all the gif images) inside the setTimeout function.