Search code examples
animationresetwebp

Reset a webp animation so that it will play from frame 1, restart animated webp


This issue has been discussed for gif files. Here is what DID NOT WORK for webp files. Script starts with,

var animatedWebpImg = document.getElementById('idOfTheWebpInsideAnImgElement');

First failed attempt,

animatedWebpImg.style.display = "none";
setTimeout(function() {  animatedWebpImg.style.display = "block";  },100);

Second, we have tried removeChild() and appendChild() with exactly the same logic but that didn't work either.

Finally, getting close however without success,

var srcOfTheImg = animatedWebpImg.src;
animatedWebpImg.src = "";                 // empty and then back to original
animatedWebpImg.src = srcOfTheImg;

Solution

  • Here is what worked,

    let srcOfTheImg = animatedWebpImg.src;
    animatedWebpImg.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
    setTimeout(function () {  animatedWebpImg.src = srcOfTheImg;  },100);
    

    Here instead of emptying the src to nothing, we fill it with a transparent pixel that is an invisible something. It is uncertain if this is necessary for every single browser. The certainly necessary thing is the delay between the emptying and the reverting.

    If 100ms is unacceptably long for you, you can use requestAnimationFrame() instead of setTimeout(). Like

    let srcOfTheImg = animatedWebpImg.src;
    requestAnimationFrame(revert);
    function revert() { animatedWebpImg.src = srcOfTheImg; }