簡體   English   中英

javascript 中的 2d 瓷磚 Map 僅顯示一部分

[英]2d Tile Map in javascript only showing a portion

我正在使用 2d tilemap,當我嘗試在 canvas 中渲染它時,它會出現傾斜,它應該在 canvas 周圍有一個邊框,但我在 ZFCC790C72A86190DE1B549D0DDC61左上角得到了幾個矩形圖塊完整的 canvas

這是我的代碼

<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <canvas id="c" style="border:3px solid black;"></canvas>
  <script>
    var c = document.getElementById("c");
    var ctx = c.getContext("2d");
    var tilesize = 50;
    c.style.width = (10 * tilesize) + "px";
    c.style.height = (10 * tilesize) + "px";
    var w = c.width;
    var h = c.height;

    var cols = 10;
    var rows = 10;
    var map = [
    [1,1,1,1,1,1,1,1,1,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,0,0,0,0,0,0,0,0,1],
    [1,1,1,1,1,1,1,1,1,1]
    ]


    function drawmap() {
      for(var y = 0; y < map.length; ++y) {
        for(var x = 0; x < map[y].length; ++x) {
          if(map[y][x] == 1){
            ctx.fillRect(x*tilesize,y*tilesize,tilesize,tilesize)
          }
        }
      }

    }

    setInterval(update,10);
    function update(){
      ctx.clearRect(0,0,w,h);
      drawmap()
    }

  </script>
</body>
</html>

要為 canvas 提供預期像素數的寬度和高度,您應該設置widthheight屬性。 設置樣式時,實際上並沒有改變坐標系,只是拉伸 canvas:可見單位的數量不會因此而改變。

所以改變:

c.style.width = (10 * tilesize) + "px";
c.style.height = (10 * tilesize) + "px";

至:

c.width = 10 * tilesize;
c.height = 10 * tilesize;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM