




本文详解 canvas 绘制 8×8 棋盘时常见的坐标逻辑错误,指出原代码中 `posy` 未重置导致列错位的根本原因,并提供结构清晰、可读性强的双重解决方案:完整双循环法与优化单循环法(利用黑色背景仅绘白格)。
在使用 HTML
✅ 正确思路应明确区分「行」与「列」:每 8 个方格为一行,行内 posX 递增,行末需重置 posY 并推进 posX。
const canvas = document.getElementById("mainCanvas");
const 
ctx = canvas.getContext("2d");
const sWidth = 75;
const sHeight = 75;
// 遍历 8 行 × 8 列
for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
const posX = col * sWidth;
const posY = row * sHeight;
// 棋盘配色:(row + col) % 2 === 0 → 白格;否则黑格(背景为黑,可省略黑格绘制)
if ((row + col) % 2 === 0) {
ctx.fillStyle = "white";
ctx.fillRect(posX, posY, sWidth, sHeight);
}
}
}? 优势:逻辑直白,行列索引清晰,便于扩展(如添加点击交互、高亮等);fillRect() 替代 beginPath()+rect()+fill() 更简洁高效。
若坚持单循环,需显式计算行列:
const totalSquares = 64;
for (let i = 0; i < totalSquares; i++) {
const row = Math.floor(i / 8); // 当前行号(0~7)
const col = i % 8; // 当前列号(0~7)
const posX = col * sWidth;
const posY = row * sHeight;
if ((row + col) % 2 === 0) {
ctx.fillStyle = "white";
ctx.fillRect(posX, posY, sWidth, sHeight);
}
}通过明确行列关系并采用声明式坐标计算(而非状态式累加),即可彻底解决“方格不显示在右侧”的问题。推荐初学者优先使用双循环方案——清晰胜于技巧,稳定优于精简。