how to restart animated gifs
複数gifのスライドショーそれぞれ最初から再生させる。
<html> <head> <style> body{ margin: 0px; padding: 0px; color: #000; background-color: #008800; } .container { width: 100%; height: 100%; image-rendering: pixelated; } .bg0{ background-size: contain; background-repeat: repeat; background-position: center; } </style> <script> var gifs = [ { "url":"gif_animation_067c.gif", "duration":7, "base64":"", "bgColor":"#ff0000" }, { "url":"gif_animation_038.gif", "duration":7, "base64":"", "bgColor":"#ffff00" }, { "url":"gif_animation_007.gif", "duration":4.3, "base64":"", "bgColor":"#ff000ff" } ]; var loadedCount = 0; var loadedFlag = false; var animeIndex = 0; var loopCount = 0; function loadImg(loadedIndex){ if(loadedIndex >= gifs.length){ console.log("画像ロード終了"); return; } //base64で読み込む toDataUrl(gifs[loadedIndex].url,function(img_base64){ console.log("onload " + loadedIndex); gifs[loadedIndex].base64 = img_base64; loadedCount++; loadImg(loadedIndex+1); }); } //base64で読み込む function toDataUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { var reader = new FileReader(); reader.onloadend = function() { callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.responseType = 'blob'; xhr.send(); } //アニメ再生 function playAnime(){ console.log("playAnime " + animeIndex); //base64に乱数を追加 var data = gifs[animeIndex].base64; data = data.replace("image/gif","image/gif;rnd="+Math.random()); //base64を表示 var elem = document.getElementById("anime"); elem.style.backgroundImage="none"; elem.style.backgroundImage="url('" + data + "')"; elem.style.backgroundColor = gifs[animeIndex].bgColor; if(loopCount==0){ elem.style.backgroundPosition="center"; elem.style.backgroundSize = "contain"; }else{ elem.style.backgroundPosition = 100*Math.random() + "% " + 100*Math.random() + "%"; if(Math.random()<0.25) elem.style.backgroundPosition="center"; elem.style.backgroundSize = (30 + 100 * Math.random()) + "%"; } //duration過ぎたら次へ setTimeout(playAnime,gifs[animeIndex].duration*1000); //インクリメント animeIndex++; if(animeIndex>=gifs.length){ animeIndex=0; loopCount++; if(loopCount==10)loopCount=0; } } window.onload=function(){ //画像群をロードする loadImg(0); //ロードをチェック (function loop(){ if(loadedCount>=1 && !loadedFlag){ //一個でもロードされたらアニメ再生 loadedFlag=true; playAnime(); }else{ window.requestAnimationFrame(loop); } })(); }; </script> </head> <body> <div id="anime" class="container bg0"></div> </body> </html>