
本文详解 canvas 绘制 8×8 棋盘时常见的坐标逻辑错误,指出原代码中 `posy` 未重置导致列错位的根本原因,并提供结构清晰、可读性强的双重解决方案:完整双循环法与优化单循环法(利用黑色背景仅绘白格)。
在使用 HTML
✅ 正确思路应明确区分「行」与「列」:每 8 个方格为一行,行内 posX 递增,行末需重置 posY 并推进 posX。
✅ 推荐方案一:双层 for 循环(最直观、易维护)
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);
}
}⚠️ 关键注意事项
- 勿依赖 posY += 75 累加:单循环中 posY 必须由行号动态计算(row * sHeight),而非持续累加后尝试“修正”。
- ctx.closePath() 非必需:fillRect() 是原子操作,无需路径操作;若用 rect(),也只需 fill(),closePath() 对矩形无意义。
- 性能提示:黑色背景上仅绘制白格可减少 50% 绘制调用,但双循环结构更利于后期维护(例如切换主题色、添加边框等)。
- 尺寸校验:8 × 75 = 600,恰好匹配
通过明确行列关系并采用声明式坐标计算(而非状态式累加),即可彻底解决“方格不显示在右侧”的问题。推荐初学者优先使用双循环方案——清晰胜于技巧,稳定优于精简。










