【发布时间】:2016-10-29 03:06:13
【问题描述】:
我正在尝试生成一个基于图块的地图,到目前为止它工作得很好,但是在用图像替换所有“测试矩形”来表示地面、路径、一些房屋等之后(在这个万一所有的图像都是相同的),没有一个图像被绘制下来。
我在这里做错了什么?我也得到零错误。
这里的代码被剪断了:
// 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
【问题讨论】:
标签: javascript html for-loop canvas drawimage