首页 > 解决方案 > 从数组中在画布上绘制正方形

问题描述

我有一个关于如何使用嵌套数组中的坐标在画布上绘制正方形的问题。这个想法是突出一些方块,以便玩家知道他可以在这些方块上移动。

绘制这些正方形的函数会在之后调用,因此不会再次绘制整个画布。

我知道如何在精确的正方形上显示图像,但不明白如何遍历嵌套数组,以便画布可以使用它再次绘制一些红色正方形。

如何将“数组坐标”转换为画布绘图方法可用的值。

还是问题来自availableSquare 和chartBoard 之间的差异?

由于我没有找到任何关于此的主题,我希望我的示例足够详细。

function Game(width, height) {
  this.width = width;
  this.height = height;
}
const game = new Game(10, 10)
const chartBoard = [];
const availableSquares = [
  [6, 6],
  [6, 7],
  [6, 8]
]


// The nested arrays with all the possible position
function createBoard(width, height) {
  for (let i = 0; i < width; i++) {
    const row = [];
    chartBoard.push(row);
    for (let j = 0; j < height; j++) {
      const col = {};
      row.push(col);
    }
  }
  return chartBoard;
};
createBoard(game.width, game.height);
console.log(chartBoard)

// Display the array on the canvas
const ctx = $('#board').get(0).getContext('2d');

function drawBoard(width, height) {
  for (let i = 0; i < width; i++) {
    for (let j = 0; j < height; j++) {
      ctx.strokeStyle = 'rgba(0, 0, 0, 0.7)';
      ctx.beginPath();
      ctx.strokeRect(j * 64, i * 64, 64, 64);
      ctx.closePath();
    }
  }
};
drawBoard(game.width, game.height);

// Function to highlight the squares from the array availableSquares
//        function showAvailableMovement(array) {
//            for (let i = 0; i < array.length; i++) {
//                for (let j = 0; j < array[i].length; j++) {
//
//                    ctx.strokeStyle = 'red';
//                    ctx.beginPath();
//                    ctx.strokeRect(j * 64, i * 64, 64, 64);
//                    ctx.closePath();
//                }
//            }
//        };
//        showAvailableMovement(availableSquares);
body {
  background-color: black;
}

#board {
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas id="board" width="640" height="640"></canvas>

标签: javascriptjqueryarrayscanvas

解决方案


你实际上真的很接近,你只是混淆了你的 x 和 y 值:

// Function to highlight the squares from the array availableSquares
function showAvailableMovement(array) {
    for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array[i].length; j++) {

            let x = array[i][0];
            let y = array[i][1];

            ctx.strokeStyle = 'red';
            ctx.beginPath();
            ctx.strokeRect(x * 64, y * 64, 64, 64);
            ctx.closePath();
        }
    }
};
showAvailableMovement(availableSquares);

推荐阅读