2016-07-27 82 views
4

我想要做一個從網頁中加載的多個GIF組裝成的動畫。同時加載圖像

所以,我會把gif放在另一個之上來做到這一點。 爲了實現這個功能,gif需要在同一時間加載。 我如何在網絡編程中做到這一點?

+0

我創造了這個小提琴:https://jsfiddle.net/baz3ynt1/5/它使用javascript來加載gif(你不能強制它們同時加載),然後創建空的'img' DOM元素並設置它們的'src'屬性在同一時間...我試過它在Firefox和它的作品,但它不在IE 11中,我不知道爲什麼。目前無法在Chrome中嘗試。 –

回答

2

我的小提琴https://jsfiddle.net/baz3ynt1/9/是使用JavaScript做圖像加載一個答案異步,但是同時將它們添加到DOM以同步啓動它們的動畫。我不認爲你可以強制瀏覽器在特定時間完成加載圖像,因爲瀏覽器不知道加載資源需要多長時間。

每個的Gif被使用

gif = new Image(); 
gif.src = 'image url'; 
gif.onload = handleLoading(); 

handleLoading()功能加載了觸發startAnimation()功能的所有照片與圖像觸發其onload事件:

function handleLoading() 
{ 
    // numLoadedGifs is a counter previously initialized as zero 
    // gifUrls is an array of the urls to load 
    numLoadedGifs++; 
    if (numLoadedGifs === gifUrls.length) 
    { 
     // now all images are completely loaded 
     startAnimation(); 
    } 
}; 

然後startAnimation()函數將先前創建的img元素(存儲在一個數組中)作爲子元素放到<div id="animation">上,但爲了讓它們同時運行,它們的src屬性被重新設置,並重新設置:

function startAnimation() 
{ 
    var animationDiv = document.getElementById('animation'); 
    for (var index in gifList) 
    { 
     var img = animationDiv.appendChild(gifList[index]); 
     img.classList.add('cloth'); 
     img.src = ''; 
     img.src = gifUrls[index]; 
    } 
}; 

我在Firefox和IE 11測試它(重置src是什麼使得它在IE 11的工作)。


編輯:顯然IE並不總是不夠快,追加圖像,然後重置其src的一步到位,所以https://jsfiddle.net/baz3ynt1/10/拆分兩個任務:

function startAnimation() 
{ 
    var animationDiv = document.getElementById('animation'); 
    for (var index in gifList) 
    { 
     var img = animationDiv.appendChild(gifList[index]); 
     img.classList.add('cloth'); 
    } 
    for (var index in gifUrls) 
    { 
     gifList[index].src = ''; 
     gifList[index].src = gifUrls[index]; 
    } 
}; 
2

的GIF將需要在精確的同時

有一個叫拼合CSS技術加載。

相反裝載4周100×100像素的GIF(或PNG),加載一個200x200像素的GIF,然後在一系列的100×100像素的div,你重新定位background-image,以便它顯示只把部分的所需的200×200像素的圖片顯示:

.box { 
 
float: left; 
 
width: 100px; 
 
height: 100px; 
 
margin: 6px 12px 6px 0; 
 
background-image: url(http://placehold.it/200x200); 
 
} 
 

 
.top-left { 
 
background-position: 0 0; 
 
} 
 

 
.top-right { 
 
background-position: -100px 0; 
 
} 
 

 
.bottom-left { 
 
background-position: 0 -100px; 
 
} 
 

 
.bottom-right { 
 
background-position: -100px -100px; 
 
} 
 

 
.original { 
 
clear: left; 
 
width: 200px; 
 
height: 200px; 
 
}
<div class="box top-left"></div> 
 
<div class="box top-right"></div> 
 
<div class="box bottom-left"></div> 
 
<div class="box bottom-right"></div> 
 
<div class="box original"></div>

+0

這是一個很好的技術,它可以用於我的任務,但我設計了迄今爲止不會使用這種技術的圖像。我有一個人的設計,用戶可以爲這個人選擇他想要的任何衣服。我可以選擇上傳用戶選擇的衣服並將其作爲服務器上的圖像,或者預先加載網頁中每個布料的每個圖像並將其放在人的上面。我選擇了第二種方法,我正在尋找另一種技術。我不認爲你提供的將會這樣做。 –

+0

另一種方法是使用javascript檢測何時加載了所有圖像並僅在該時刻開始動畫。 – Rounin