2011-04-14 60 views
3

我試圖將10個不同的圖像加載到畫布中。我的計劃是最終爲這些圖像製作動畫,但現在它們似乎正在相互覆蓋。這裏是我的代碼:是否可以在HTML5畫布中使用多個圖像?

var DrawLetters = function() 
{ 
    for (i = 0; i < howManyLetters; i++) 
    { 
     thisWidth = letters[i][0]; 
     thisHeight = letters[i][1]; 
     imgSrc = letters[i][2]; 
     letterImg = new Image(); 
     letterImg.onload = function() 
     { 
      context.drawImage(letterImg,thisWidth,thisHeight); 
     } 
     letterImg.src = imgSrc; 
    } 
}; 

字母是一個包含10個元素的數組,其中每個元素包含圖像的路徑。任何幫助,將不勝感激。

+0

你知道你在for循環中使用全局變量嗎? – Phrogz 2011-04-14 15:49:38

+0

我會的。這只是目前的概念證明,並不意味着通過JSLint分析。我只是想讓這些作品能夠在全面書寫之前證明我可以做我想做的事情。 – Dexter 2011-04-15 12:57:13

回答

4

我試過你的代碼,onload方法總是使用變量的最後值,而不是數組迭代時的值。

嘗試X和Y設置爲圖像對象的屬性:

// I assume you are storing the coordinates where the letters must be 
letterImg.setAtX = letter[i][XPOS]; 
letterImg.setAtY = letter[i][YPOS]; 

和在onload:

context.drawImage(this, this.setAtX, this.setAtY); 

this是圖像提高onload事件。

編輯我改變了用來攜帶座標的屬性。現在他們被設置爲A/X。你不能使用x和y,因爲它們是保留的。

+0

工作就像一個魅力!謝謝! – Dexter 2011-04-14 14:42:46

+0

歡迎。請享用! – helios 2011-04-14 15:55:47

0

您必須每次重新定位繪製起始位置,以免圖像被覆蓋。

[context . drawImage(image, dx, dy, dw, dh)][1] 

鏈接上有一張圖片,解釋每個參數的含義。

1

你在同一點上繪製它們。 drawImage並不關心給定參數的高度或寬度;它只是想要一個圖像和一個座標。請參閱https://developer.mozilla.org/en/Canvas_tutorial/Using_images

因此,您需要爲圖片提供更多數據;是這樣的:

thisWidth = letters[i][0]; 
    thisHeight = letters[i][1]; 
    imgSrc = letters[i][2]; 
    thisX = letters[i][3]; //<--- 
    thisY = letters[i][4]; //<--- 
    letterImg = new Image(); 
    letterImg.onload = function() 
    { 
     context.drawImage(letterImg, thisX, thisY, thisWidth, thisHeight); 
     //or, just 
     context.drawImage(letterImg, thisX, thisY); 
    } 
    letterImg.src = imgSrc; 

編輯:只是有一個想法 - 你可以做到這一點dymagically:

context.drawImage(letterImg, letters[i-1][0]+thisWidth, letters[i-1]+thisHeight, thisWidth, thisHeight); 

用這種方式,你必須檢查的東西,但我覺得你得到的意向整體。

+0

對不起,我的變量名稱不清楚。它們不應該是這個寬度和這個高度,那些實際上是X,Y的座標,它們都是獨一無二的。 – Dexter 2011-04-14 14:34:52