这是我的剧本,我似乎无法弄清楚什么是错的,我想绘制一张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;
}
}
如果有人可以帮我把我的瓷砖画得非常感谢,谢谢!
答案 0 :(得分:2)
您必须等待图片加载。该图像不是DOM的一部分,因此等待加载文档无济于事。
您需要为image.onload
插槽放置一个处理程序,并在调用该代码时触发重绘。
正常程序是
src
值只有在调用注册事件时才能使用图像对象。
棘手的部分是,根据浏览器,如果图像已经在缓存中,则设置src
后图像可能立即生效,因此当您不遵循正确的程序时,事情可能显然仍然有效(但是当加载需要互联网访问时,它们在实际情况下不起作用。)
答案 1 :(得分:0)
我可以看到两个主要问题:
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;
}
}
另外请务必仔细检查图像路径。