2014-09-27 89 views
0

當我使用透明PNG時,ctx.drawImage()不起作用,但在使用常規PNG時卻起作用。Canvas ctx.drawImage無法使用透明PNG

var context = document.getElementById("canvas").getContext('2d'); 
.... 
function draw(img, x, y){ 
    context.drawImage(img, x, y); 
} 

//actulaly there is loop here, but for simplicity I put only this. 
var img = new Image(); 
img.src = "images/a.png"; 
img.onload = draw(img, 10, 10); 

如果我使用常規的PNG圖像,它的工作原理是,但使用背景已刪除的透明度的PNG,它不起作用。 你們有什麼想法,爲什麼?謝謝。

回答

1

img.onload需要函數引用而不是函數調用。

所以做到這一點:

img.onload=function(){draw(img,10,10);} 

如果您需要加載許多圖像,這裏是調用start()函數之前完全加載所有圖像的圖像預載:

// image loader 

// put the paths to your images in imageURLs[] 
var imageURLs=[]; 
// push all your image urls! 
imageURLs.push(""); 
imageURLs.push(""); 

// the loaded images will be placed in images[] 
var imgs=[]; 

var imagesOK=0; 
loadAllImages(start); 

function loadAllImages(callback){ 
    for (var i=0; i<imageURLs.length; i++) { 
     var img = new Image(); 
     imgs.push(img); 
     img.onload = function(){ 
      imagesOK++; 
      if (imagesOK>=imageURLs.length) { 
       callback(); 
      } 
     }; 
     img.onerror=function(){alert("image load failed");} 
     img.crossOrigin="anonymous"; 
     img.src = imageURLs[i]; 
    }  
} 

function start(){ 

    // the imgs[] array now holds fully loaded images 
    // the imgs[] are in the same order as imageURLs[] 

} 
+0

OK,我會嘗試,謝謝。 – Alex 2014-09-27 22:53:18

+0

仍然無法正常工作。函數draw()被稱爲11550次(我有一個console.log),但它什麼也沒畫。有趣的是,控制檯也沒有錯誤。如果我使用另一個不透明的PNG文件,它可以工作。 – Alex 2014-09-27 23:05:05

+0

Ahhh ...通過循環11500次...好的,如果'var img'在一個循環內,那麼在第一次迭代'img'之前,循環的下一個迭代將會替換'img'完全讀取。因此,確保循環的下一次迭代在第一次onload完成之前不會執行。可能無關,但將.onload放在.src之前(以防萬一)。 – markE 2014-09-27 23:12:59