2016-08-17 72 views
0

我試圖創建一個圖像對象的數組,並在窗口加載到畫布後加載圖像。Javascript - 爲畫布創建一個圖像對象數組?

這裏是我的代碼:

var canvasObj = document.getElementById('myCanvas'); 
var ctx = canvasObj.getContext('2d'); 
var imgsrcs = ["1.png", "2.png", "3.png"]; 
var imgs = []; 
for(var i=0; i<imgsrcs.length; i++){ 
    imgs[i] = new Image(); 
    imgs[i].onload = function() { 
     ctx.drawImage(imgs[i], xb,yb); 
    } 
    imgs[i].src = imgsrcs[i]; 
} 

不過,我得到這個錯誤控制檯:

TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageBitmap. 
ctx.drawImage(imgs[i], xb,yb); 

我在做什麼錯?

預先感謝

回答

2

的時候被調用onload事件,for-loop因此被迭代的ilength+1,因爲有在索引length+1沒有元件,undefined作爲第一個參數傳遞給ctx.drawImage

drawImage方法中使用this上下文,其中this === Image-Object

var canvasObj = document.getElementById('myCanvas'); 
 
var ctx = canvasObj.getContext('2d'); 
 
var imgsrcs = ["http://i.imgur.com/gwlPu.jpg", "http://i.imgur.com/PWSOy.jpg", "http://i.imgur.com/6l6v2.png"]; 
 
var xb = 0, 
 
    yb = 0; 
 
var imgs = []; 
 
for (var i = 0; i < imgsrcs.length; i++) { 
 
    imgs[i] = new Image(); 
 
    imgs[i].onload = function() { 
 
    console.log(imgs[i]); //Check this value 
 
    ctx.drawImage(this, xb, yb); 
 
    xb += 50; 
 
    yb += 50; 
 
    } 
 
    imgs[i].src = imgsrcs[i]; 
 
}
<canvas id="myCanvas"></canvas>

+1

感謝您的回答和洞察力。有用。 – ponir