用Javascript对象在画布上画板

时间:2019-01-17 08:46:40

标签: javascript object canvas

我想用Javascript创建一个简单的游戏,并使用画布显示它。 我有一个用于木板的对象,并且不了解如何使用先前生成的木板对象在画布上绘制上色和行。

我试图使函数drawBoard(Board的原型)使用this.width和this.height。但是它不使用这些值。

我对如何在此功能板上使用对象属性(宽度和高度)重用一无所知。在画布上相当新。

<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-compatible" content="IE-edge">
<meta name="viewport" content="width=device-width, initial-scale-1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.css">
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

  <title>Lava Temple</title>

<style>
* {
  padding: 0;
  border: 0;
}

body{
  background-color: #181818;
}

#board {
  display: block;
  background-color: white;
  margin: 0 auto;
  margin-top: 100px;
}
</style>

</head>
<body>
    <canvas id="board" width="800" height="800"></canvas>

<script>

function Board(width, height) {
  this.width = width;
  this.height = height;
  this.chartBoard = [];

  for (var i = 0; i < this.width; i++) {
    const row = [];
    this.chartBoard.push(row);
    for (var j = 0; j < this.height; j++) {
        const col = {};
        row.push(col);
    }
  }
}

let board = new Board(10, 10);
console.log(board);

const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');

Board.prototype.drawBoard = drawBoard;

function drawBoard() {

  for (var i = 0; i < this.width; i++) {
    for (var j = 0; j < this.height; j++) {
        ctx.beginPath();
        ctx.strokeStyle = 'black';
        ctx.strokeRect(j * 80, i * 80, 80, 80);
        ctx.closePath();
    }
  }
}

drawBoard();

</script>

</body>
</html>

实际结果:在控制台中可见一个画布和一个木板对象。

预期结果:该木板创建时也用黑色笔画绘制在画布上。

为什么:该棋盘对象将包含玩家/武器...

1 个答案:

答案 0 :(得分:2)

您需要使用Board.prototype.drawBoard = function() {....,然后在调用drawBoard()时这样称呼:board.drawBoard(),因为它是board对象的方法。

function Board(width, height) {
  this.width = width;
  this.height = height;
  this.chartBoard = [];

  for (var i = 0; i < this.width; i++) {
    const row = [];
    this.chartBoard.push(row);
    for (var j = 0; j < this.height; j++) {
      const col = {};
      row.push(col);
    }
  }
}

Board.prototype.drawBoard = function() {
  for (var i = 0; i < this.width; i++) {
    for (var j = 0; j < this.height; j++) {
      ctx.beginPath();
      ctx.strokeStyle = "black";
      ctx.strokeRect(j * 80, i * 80, 80, 80);
      ctx.closePath();
    }
  }
};

let board = new Board(10, 10);

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

board.drawBoard();
* {
  padding: 0;
  border: 0;
}

body{
  background-color: #181818;
}

#board {
  display: block;
  background-color: white;
  margin: 0 auto;
  margin-top: 100px;
}
<canvas id="board" width="800" height="800"></canvas>