簡體   English   中英

用Javascript對象在畫布上畫板

[英]Draw a board on canvas with Javascript objects

我想用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>

實際結果:在控制台中可見一個畫布和一個木板對象。

預期結果:該板創建時也在黑色筆划上繪制在畫布上。

原因:此棋盤對象將包含玩家/武器...

您需要使用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> 

暫無
暫無

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

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