2012-01-30 127 views
1

這可能是一個奇怪的解釋: 我想動態創建一個畫布集合,其中將有一個單一的圖像。這顯示(經過很多麻煩和擺脫onload事件),但當我嘗試刷新頁面,我有時在屏幕上什麼都沒有。 當我使用onload事件(等待圖像加載)時,它不會顯示或顯示上一個畫布中的所有內容。循環創建多個畫布,多個圖像並不總是顯示圖像

下面是代碼片段:

var sources = []//the array that contains the images 
var divCanvas = document.getElementById('showcase-wrapper') 
for(var i=0; i<sources.length; i++){ 
    img = new Image() 
    img.src = sources[i] 
    canvas = document.createElement('canvas') 
    $(canvas).attr('id', i) 
    canvas.height=300 
    canvas.width=200 
    var context = canvas.getContext('2d'); 
    //onload commented out allows expected display 
    //img.onload = function() { 
    context.drawImage(img, 0, 0); 
    //} 
    divCanvas.appendChild(canvas) 
} 

我所看到的,似乎看起來像我的,嘗試了不少,但無濟於事許多職位。

+1

必須使用onload事件,否則這是一個競爭條件的圖像是否已加載與否。你可能只是有一個與你以前的代碼錯誤。 – 2012-01-31 13:26:25

+0

只是嘗試onload,只有最後一個圖像顯示其他人不顯示,即使畫布創建爲他們顯示到... – AKFourSeven 2012-01-31 14:06:18

回答

1

對於一致的行爲,您必須使用onload。如果您沒有在裝入圖像之前執行畫布繪圖代碼,並且不會繪製所需的圖像。

可能是因爲Image在事件觸發之前收集垃圾,因此不會調用將要吸引到其他畫布的onload

嘗試增加

var images = []; 

在你的代碼的開始和

images.push(img); 

img = new Image()行之後。

如果這不起作用,請嘗試先將這些圖像添加到DOM樹 - img.setAttribute('style', 'display: none'),以便您不會看到它們,並且它們不會干擾文檔結構。

+0

我試過解決方案之一,它會顯示在最後一個畫布上的所有圖像(一個在其他人之上),然後我嘗試瞭解決方案二,沒有什麼會顯示,但我終於找到了解決方案(我將在下一篇文章中包括) – AKFourSeven 2012-02-03 10:45:03

2

我認爲這個問題是觸發img.onload事件之前VAR上下文覆蓋。 img.onload事件僅具有對全局範圍的引用。這就是爲什麼只有最後一張圖像出現。您需要在事件中找到正確的上下文。

我不能直接測試你的代碼,但我想應該是這樣的:

var sources = []//the array that contains the images 
var divCanvas = document.getElementById('showcase-wrapper') 
for(var i=0; i<sources.length; i++){ 
    img = new Image(); 
    img.src = sources[i]; 
    img.id = i; //Allow img to remember its corresponding canvas/context 
    canvas = document.createElement('canvas'); 
    $(canvas).attr('id', i); 
    canvas.height=300; 
    canvas.width=200; 
    var context = canvas.getContext('2d'); 
    divCanvas.appendChild(canvas); 

    img.onload = function() { 
     //Use the image id to get the correct context 
     var canvas = document.getElementById(this.id); 
     var context = canvas.getContext('2d'); 
     context.drawImage(this, 0, 0); 
    } 
} 
+0

以及它並沒有真正起作用...... 來自mozilla developper網絡的例子確實有效! – AKFourSeven 2012-02-06 10:59:09