[英]Canvas.drawImage simply just does not draw the image
我正在嘗試生成一個基於圖塊的地圖,到目前為止工作得很好,但在用圖像替換所有“測試矩形”以表示地面,路徑,一些房屋等(在這種情況下是它的所有這些圖像相同的圖像),沒有一個圖像被繪制。
我在這做錯了什么? 我也得到零錯誤。
下面是代碼剪輯:
// generate a large map
Map.prototype.generate = function(){
var ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = this.width;
ctx.canvas.height = this.height;
var rows = ~~(this.width/<?php echo $GAME['map']['tileSize'] + $GAME['map']['tileBorder']; ?>) + 1;
var columns = ~~(this.height/<?php echo $GAME['map']['tileSize'] + $GAME['map']['tileBorder']; ?>) + 1;
ctx.save();
// Here i wanted to check if the image gets drawn right besides the player
var testImage = document.createElement('img'); // Also tried new Image();
testImage.onload = (function () {
console.log(testImage + "-test");
ctx.drawImage(testImage, 1000, 1000, <?php echo $GAME['map']['tileSize']; ?>, <?php echo $GAME['map']['tileSize']; ?>);
}());
testImage.src = "http://192.168.0.140/img/terrain.png";
var imgs = [];
var imgIndex = 0;
<?php echo "for (var y = 0, i = ".$tilesToLoad['xStart']."; i < ".($tilesToLoad['xStart'] + $GAME['map']['chunkSize'])."; y+=".($GAME['map']['tileSize'] + $GAME['map']['tileBorder']).", i++) {"; ?>
<?php echo "for (var x = 0, j = ".$tilesToLoad['yStart']."; j < ".($tilesToLoad['yStart'] + $GAME['map']['chunkSize'])."; x+=".($GAME['map']['tileSize'] + $GAME['map']['tileBorder']).", j++) {"; ?>
imgs[imgIndex] = document.createElement('img');
imgs[imgIndex].onload = (function () {
console.log(imgs[imgIndex] + "-" + imgIndex + "-" + x + "-" + y);
ctx.drawImage(imgs[imgIndex], x, y, <?php echo $GAME['map']['tileSize']; ?>, <?php echo $GAME['map']['tileSize']; ?>);
}());
imgs[imgIndex].src = "http://192.168.0.140/img/terrain.png";
imgIndex += 1;
}
}
ctx.restore();
// store the generate map as this image texture
this.image = new Image();
this.image.src = ctx.canvas.toDataURL("image/png");
// clear context
ctx = null;
}
console.log輸出:
[object HTMLImageElement]-test
[object HTMLImageElement]-0-0-0
[object HTMLImageElement]-1-41-0
[object HTMLImageElement]-2-82-0
[object HTMLImageElement]-3-123-0
它沒有達到預期的效果,因為您已將onload函數寫為IIFE 。 它在分配src之前立即執行該函數,並且沒有將onload分配給該函數。
將第一個onload分配更改為:
testImage.onload = function () {
console.log(testImage + "-test");
ctx.drawImage(testImage, 1000, 1000, <?php echo $GAME['map']['tileSize']; ?>, <?php echo $GAME['map']['tileSize']; ?>);
};
我在那里做的就是刪除外括號。 后來的任務也是如此:
imgs[imgIndex].onload = function () {
console.log(imgs[imgIndex] + "-" + imgIndex + "-" + x + "-" + y);
ctx.drawImage(imgs[imgIndex], x, y, <?php echo $GAME['map']['tileSize']; ?>, <?php echo $GAME['map']['tileSize']; ?>);
};
我建議刪除ctx = null;
賦值因為如果這在onload事件之前執行,那么它們將無法在畫布上繪制圖像,而是會得到Uncaught TypeError:無法讀取null的屬性'drawImage'
另外,正如Blindman67指出的那樣,需要進行一些更改,以便在所有onload事件被觸發后從畫布中創建圖像。 為此,您可以使用計數器,類似於此示例 ,其中在加載一組圖像后顯示警報。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.