我只是不能得到這個爲我工作。使用drawImage()繪製多個圖像在畫布上的問題
我試圖使用drawImage()繪製多個圖像到畫布。我覺得我大大忽視了一些小事。
它應該畫18張牌。它將從左側開始50px,從頂部開始下降,並繪製每張牌100w * 150h。每張卡片圖像之間應該有25px。畫布尺寸設置爲825w * 600h。
試圖用簡單的Javascript(沒有jQuery)完成此操作。任何幫助表示讚賞。
// Draw the cards to the canvas.
function drawCards()
{
// Starting positions.
var x = 50;
var y = 50;
// Counter that will hold current card position.
var cardCount = 0;
var img = new Image(100, 150);
// How many rows.
for (var row = 0; row < 3; row++)
{
// How many columns.
for (var column = 0; column < 6; column++)
{
// Store the current card.
var card = memoryDeck[cardCount];
// Check if the card is flipped, if it is set an image with url to face card.
if (card.flipped == true)
{
img.onload = function() {
ctx.drawImage(this, x, y, 100, 150);
}
img.src = card.faceImage;
}
// Otherwise set image url to back of card.
else
{
img.onload = function() {
ctx.drawImage(this, x, y, 100, 150);
}
img.src = card.backImage;
}
// Increase the x position (the width of a card, plus the space in between), and the current card position being stored.
x += 125;
cardCount++;
}
// We are on a new row, reset the column card position and increase the row card position.
x = 50;
y += 175;
}
}
這解決了我的一半問題。謝謝!我仍然需要弄清楚它爲什麼只畫出最後一張圖像,但是......:/ –
看起來我沒有完全應用這個。使用這個,做了些微的調整,並設法修復整個事情。非常感謝! –