2016-01-21 91 views
0

我正在嘗試設置一個具有圖片背景的畫布。我想讓圖像變量,但這是一個不同的討論。使用圖像二維設置畫布

這是我的代碼。

var canvas = document.getElementsByTagName('canvas')[0]; 

var img = document.createElement('img'); 

img.onload = function() { alert(img.width + ' x ' + img.height); }; 

img.src='images/maps/de_dust2.jpg'; 

canvas.width = img.width; 
canvas.height = img.height; 

當頁面加載時,我得到正確的像素高度和寬度的警報,但畫布不顯示。

任何幫助表示讚賞。

回答

0
var canvas = document.getElementsByTagName('canvas')[0]; 

var img = document.createElement('img'); 

img.onload = function() { 
    // you need to have thes in the onload, to have img width, height > 0 
    canvas.width = img.width; 
    canvas.height = img.height; 
    alert(img.width + ' x ' + img.height); 
}; 

img.src='images/maps/de_dust2.jpg'; 
+0

你知道爲什麼它需要在onload?謝謝你的方式。 –

+0

因爲只有當它完成加載圖像它知道圖像的大小。當你在img.onload之後擁有它們時,它們在加載圖像之前執行,所以你得到了0或NaN – Gavriel