[英]HTML 5 Canvas - Dynamically include multiple images in canvas
我需要在canvas
包含多個圖像。 我想通過for-loop
動態加載它們。
我嘗試了很多,但在最佳情況下僅顯示最后一張圖像。 我檢查了這個踏板,但仍然只得到最后一張圖像。
為了說明,這是我的最新代碼(基本上是另一篇文章中的代碼):
for (var i = 0; i <= max; i++)
{
thisWidth = 250;
thisHeight = 0;
imgSrc = "photo_"+i+".jpg";
letterImg = new Image();
letterImg.onload = function() {
context.drawImage(letterImg,thisWidth*i,thisHeight);
}
letterImg.src = imgSrc;
}
有任何想法嗎?
問題在於onload
事件是異步發生的,屆時循環變量已經處於最后一個值。 您可以使用閉包對其進行修復:
for (var i = 0; i <= max; i++)
{
thisWidth = 250;
thisHeight = 0;
(function(j){
var imgSrc = "photo_"+j+".jpg";
var letterImg = new Image();
letterImg.onload = function() {
context.drawImage(letterImg,thisWidth*j,thisHeight);
}
letterImg.src = imgSrc;
})(i);
}
這是解決問題的另一種方法...
letterImg
只是對圖像的引用。 因此,for循環將執行n次,並且每次letterImg
都會更改為一個新圖像。 因此,您僅獲得繪制的最新圖像。
這是代碼(當然,將maxImg
數更改為正確的值。):
images = []; //An array where images are stored.
thisWidth = 250; //This doesn't need to be inside the for-loop.
thisHeight = 0;
maxImg = 342;
//Attach an onload event to an image, that will draw it at (x, y) coordinates.
attach = function(img, x, y)
{
img.onload = function()
{
context.drawImage(img, x, y);
}
}
for (var i = 0; i <= maxImg; i++)
{
imgSrc = "photo_" + i + ".jpg";
images[i] = new Image();
images[i].src = imgSrc;
attach(images[i], thisWidth*i, thisHeight);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.