为什么这段代码无法生成图块地图?

时间:2019-03-23 05:20:37

标签: javascript

我目前正在尝试使用一些马里奥精灵为游戏创建一个tilemap。由于某些原因,没有图像正在加载,我已经尝试了所有可以想到的方法。

我尝试了以下代码来生成具有2d数组的地图:

JS:

var canvas = document.getElementById("GameCanvas")
var ctx = canvas.getContext("2d")

var testMap = [
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1]
];

        var testBlock = new Image();
        testBlock.src = "./img/52571.png"

var posX = 0;
var posY = 0;

function drawMap () {
    for (var i = 0; i < testMap.length; i++) {
    for (var j = 0; j < testMap[i].length; j++) {
        if (testMap[i][j] == 1) {
            ctx.drawImage(testBlock, 0, 0, 16, 16, posX, posY, 16, 16);
        }
        posX += 16;
    }
    posX = 0;
    posY += 16;
    };
}

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Game</title>
    </head>
<body>
    <canvas id = "GameCanvas" width = "800" height = "480"></canvas>
    <script src ='game_main.js'></script>
</body>
</html>

这里是tileset

任何人都可以提供一些有关为何无法正常工作的见解吗?

2 个答案:

答案 0 :(得分:0)

在绘制图像之前,请确保已加载图像。

您可以通过在drawMap中调用testBlock.onload来实现。

这是一个正常的演示(只需单击Run code snippet

var testMap = [
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];

var testBlock = new Image();
testBlock.onload = drawMap;
testBlock.src = "https://i.stack.imgur.com/R6JFX.png"

function drawMap() {

  var canvas = document.getElementById("GameCanvas")
  var ctx = canvas.getContext("2d")
  
  var posX = 0;
  var posY = 0;

  for (var i = 0; i < testMap.length; i++) {
    for (var j = 0; j < testMap[i].length; j++) {
      if (testMap[i][j] == 1) {
        ctx.drawImage(testBlock, 0, 0, 16, 16, posX, posY, 16, 16);
      }
      posX += 16;
    }
    posX = 0;
    posY += 16;
  };
}
<body>

  <canvas id="GameCanvas" width="160" height="96" style="border:1px solid #000000;" />

</body>

答案 1 :(得分:0)

在您的代码中定义了drawMap函数,但未调用该函数。在图像的onload上调用drawMap函数。

const canvas = document.getElementById("GameCanvas");
const ctx = canvas.getContext("2d");

var testMap = [
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0],
    [1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,1,1,1,1,1]
];

const testBlock = new Image();
testBlock.src = "https://mdn.mozillademos.org/files/5397/rhino.jpg"
testBlock.onload = drawMap;

let posX = 0;
let posY = 0;

function drawMap () {
    for (let i = 0; i < testMap.length; i++) {
    for (let j = 0; j < testMap[i].length; j++) {
        if (testMap[i][j] == 1) {
            ctx.drawImage(testBlock, 0, 0, 16, 16, posX, posY, 16, 16);
        }
        posX += 16;
    }
    posX = 0;
    posY += 16;
    };
}
<canvas id = "GameCanvas" width = "800" height = "480"></canvas>