我的瓷砖组不会出现。有什么问题?
这是一段代码:
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mapa {
border: solid 1px;
}
</style>
</head>
<body> <canvas id="mapa" height="500px" width="500px"></canvas>
<script>
var canvas = document.getElementById('mapa');
var ctx = canvas.getContext('2d');
var trawa = new Image();
trawa.src = "trawa.png";
var mapa = [
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
];
var posX = 0;
var posY = 0;
for (var x = 0; x < mapa.length; x++) {
for (var y = 0; y < mapa[x].length; y++) {
if (mapa[x][y] == 0) {
ctx.drawImage(trawa, posX, posY, 32, 32);
}
posX += 50;
}
posX = 0;
posY += 50;
}
</script>
</body>
</html>
答案 0 :(得分:0)
这里的问题是当您尝试绘制图像时图像尚未加载,您需要做的是等到它被加载。
为此您可以使用trawa.onload
,如下所示:
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#mapa
{
border: solid 1px;
}
</style>
</head>
<body>
<canvas id = "mapa" height = "500px" width= "500px"></canvas>
<script>
var canvas = document.getElementById('mapa');
var ctx = canvas.getContext('2d');
var trawa = new Image();
trawa.src = "trawa.png";
var mapa = [
[0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,0]
];
var posX = 0;
var posY = 0;
trawa.onload = function (){
for (var x = 0; x < mapa.length; x++){
for (var y = 0; y < mapa[x].length; y++)
{
if (mapa[x][y] == 0)
{
ctx.drawImage(trawa, posX, posY, 32,32);
}
posX+=50;
}
posX = 0;
posY+=50;
}
}
</script>
</body>
</html>