javascript - 从数组中在画布上绘制正方形
问题描述
我有一个关于如何使用嵌套数组中的坐标在画布上绘制正方形的问题。这个想法是突出一些方块,以便玩家知道他可以在这些方块上移动。
绘制这些正方形的函数会在之后调用,因此不会再次绘制整个画布。
我知道如何在精确的正方形上显示图像,但不明白如何遍历嵌套数组,以便画布可以使用它再次绘制一些红色正方形。
如何将“数组坐标”转换为画布绘图方法可用的值。
还是问题来自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>
解决方案
你实际上真的很接近,你只是混淆了你的 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);
推荐阅读
- python - selenium & python - 无法与 web 元素交互
- c# - 如何在 docker container/docker swarm/k8s 中降级 Entity Framework Core 迁移
- typescript - Vue Typescript 回调:this 隐含类型为 any
- mysql - MS Access:如何自动将一个也是 FK 的 PK 填充到另一个表自动递增 PK?
- python - Python - TypeError:字符串索引必须是整数
- asp.net-core - 绑定 kendo.data.SchedulerDataSource 而不会出现找不到名称“kendo”错误
- r - 识别数据是否包含某些单词,如果有,则标记为 TRUE,如果没有,则标记为 FALSE
- .net - 在 msbuild 中设置 TargetFrameworkVersion 属性会导致错误“此程序集由比当前加载的更新的运行时构建。”
- r - 如何将弹出窗口添加到折线中,当鼠标悬停在地图上的折线上时显示传单
- ios - AVAssetWriter 视频输出不播放附加音频