拼贴地图Javascript赢了

时间:2015-08-20 12:28:58

标签: javascript html



<html>

<head>
  <title>TileMap</title>
  <style>
    #canvas {
      outline: 1px solid #000;
    }
  </style>
</head>

<body>
  <canvas id="canvas" height="1000" width="1000"></canvas>
  <script>
    var canvas = document.querySelector('#canvas');
    var context = canvas.getContext('2d');

    var grass = new Image();
    var water = new Image();
    var dirt = new Image();


    grass.src = 'grass1.jpg';
    water.src = 'water.jpg';
    dirt.src = 'dirt.jpg';

    var xpos = 0;
    var ypos = 0;

    var map = [
      [0, 0, 0, 1, 0],
      [0, 0, 0, 1, 0],
      [0, 0, 0, 1, 0],
      [0, 0, 0, 1, 0],
      [0, 0, 0, 1, 0]

    ];

    for (var i = 0; i < map.length; i++) {
      for (var j = 0; j < map[i].length; j++) {

        if (map[i][j] == 0) {
          context.drawImage(grass1, xpos, ypos);
        }

        if (map[i][j] == 1) {
          context.drawImage(dirt, xpos, ypos);
        }

        if (map[i][j] == 2) {
          context.drawImage(water, xpos, ypos);
        }

        xpos += 100;
      }
      xpos = 0;
      ypos += 100;

    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;

我认为我的问题是图像尺寸都是100 X 100。

我想在javascrtipt,html和css中制作这个tile map而不使用任何jquery。

请帮助,这是我的第一个javascript项目。

1 个答案:

答案 0 :(得分:0)

您正在尝试在实际加载图像之前绘制画布。因此,在加载图像后,在函数中编写绘图部件并调用该函数。例如......

&#13;
&#13;
grass.onload = function () {
          fill_canvas(grass);       // FILL THE CANVAS WITH THE IMAGE.
      }

function fill_canvas(img) {

    ... write your canvas context here.

}
&#13;
&#13;
&#13;

将多个图像引用传递给fill_canvas()函数。它解释了here