【发布时间】:2019-03-06 09:25:55
【问题描述】:
我有一个关于如何使用嵌套数组中的坐标在画布上绘制正方形的问题。这个想法是突出一些方块,以便玩家知道他可以在这些方块上移动。
绘制这些正方形的函数在之后被调用,因此整个画布不会再次绘制。
我知道如何在精确的正方形上显示图像,但不明白如何遍历嵌套数组,以便画布可以使用它再次以红色绘制一些正方形。
如何将“数组坐标”转换为画布绘图方法可用的值。
还是问题出在 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>
【问题讨论】:
标签: javascript jquery arrays canvas