这是我的脚本,我似乎无法弄清楚出了什么问题,我想绘制一个12 * 12的瓦片地图,并且瓦片为32px-32px。当我运行页面时,磁贴不会绘制,我尝试使用parse int,如下所示,但仍然无法正常工作。
if(parseInt(mapArray[x][y]) == 0){
ctx.drawImage(rockTile, posX, posY, tileSize, tileSize);
}
这是我创建的脚本。
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = (32 * 12);
canvas.height = (32 * 12);
document.body.appendChild(canvas);
var rockTile = new Image();
rockTile.src = "../Images/dc-dngn/floor/rect_gray0.png";
var tileSize = 32;
var posX = 0;
var posY = 0;
var mapArray = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
$(document).ready(function(){
drawMap();
});
function drawMap(){
for(var x = 0; x < mapArray.length; x++){
for(var y = 0; y < mapArray[x].length; y++){
if(mapArray[x][y] == 0){
ctx.drawImage(rockTile, posX, posY, tileSize, tileSize);
}
posX += 32;
}
posX = 0;
posY += 32;
}
}
如果有人可以帮助我绘制我的瓷砖,将不胜感激,谢谢!
您可以看到两个主要问题:
document.body
它之前定义。这是解决这两个问题的代码:
// variables are defined as global variables
var posX = 0;
var posY = 0;
var tileSize = 32;
var mapArray;
var canvas;
var ctx;
var rockTile;
$(function() {
// document should be defined now
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
canvas.width = (32 * 12);
canvas.height = (32 * 12);
document.body.appendChild(canvas);
mapArray = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
// wait until the image is loaded to draw
rockTile = new Image();
rockTile.onload = drawMap;
rockTile.src = "../Images/dc-dngn/floor/rect_gray0.png";
});
function drawMap(){
posX = 0;
posY = 0;
for(var x = 0; x < mapArray.length; x++){
for(var y = 0; y < mapArray[x].length; y++){
if(mapArray[x][y] == 0){
ctx.drawImage(rockTile, posX, posY, tileSize, tileSize);
}
posX += 32;
}
posX = 0;
posY += 32;
}
}
另外,请务必仔细检查您的图像路径。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句