我在画布上创建了一系列正方形。添加了一个数字数组。如何从数字数组中添加数值。以便数字按顺序显示在方块上。我需要数组中的数字来对每个方块进行编号。我在每个方块中显示了整个数组。这是我的代码。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>javascript Canvas Array_Square</title>
<style>
body {
text-align: center;
}
#canvas {
border: 2px solid green;
background-color: lightblue;
}
</style>
</head>
<body>
<h1>javascript Canvas Array_Square</h1>
<canvas id="mycanvas"></canvas>
<script>
const canvas = document.getElementById('mycanvas');
const ctx = canvas.getContext("2d");
const CELL_SIZE = 100;
const ROWS = 4,
COLS = 4;
const CELL_COUNT = ROWS * COLS;
var cellCol = "green";
//Позиции на доске
const boardPosition = {
x: 0,
y: 0,
w: COLS * CELL_SIZE,
h: ROWS * CELL_SIZE
};
canvas.width = boardPosition.x + boardPosition.w;
canvas.height = boardPosition.y + boardPosition.h;
const cells = [];
var cellIdx = 0;
while (cellIdx < CELL_COUNT) {
drawCell(cellIdx++);
}
function drawCell(cellIdx) {
const val = cells[cellIdx];
const x = (cellIdx % COLS) * CELL_SIZE;
const y = (cellIdx / COLS | 0) * CELL_SIZE;
ctx.font = "60px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "blue";
ctx.fillRect(x, y, CELL_SIZE, CELL_SIZE);
ctx.fillStyle = cellCol;
ctx.fillRect(x + 5, y + 5, CELL_SIZE - 10, CELL_SIZE - 10);
ctx.fillStyle = "white"
const a = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8];
a.forEach((v, i) => {
<!-- const x = 10 + ((i % 5) * 25) -->
<!-- const y = 50 + (50 * Math.trunc(i / 5)) -->
<!-- ctx.fillText(v, x, y) -->
ctx.fillText(v, x + CELL_SIZE * 0.5, y + CELL_SIZE * 0.5);
})
<!-- ctx.fillText(val, x + CELL_SIZE * 0.5, y + CELL_SIZE * 0.5); -->
}
</script>
</body>
</html>
