使用canvas画一个五子棋的棋盘

<!DOCTYPE html>
<html>
<head>
<title>Canvas五子棋棋盘</title>
<style>
canvas {
  background-color: #f0e68c; /* 浅黄色背景 */
  display: block; /* 防止canvas下方出现空白 */
  margin: 50px auto; /* 居中显示 */
}
</style>
</head>
<body>

<canvas id="gobangBoard" width="450" height="450"></canvas>

<script>
const canvas = document.getElementById('gobangBoard');
const ctx = canvas.getContext('2d');

const boardSize = 15; // 棋盘大小 (15x15)
const gridSize = canvas.width / boardSize; // 格子大小

// 绘制棋盘
function drawBoard() {
  ctx.strokeStyle = '#000'; // 线条颜色
  ctx.lineWidth = 2; // 线条宽度

  for (let i = 0; i < boardSize; i++) {
    // 绘制横线
    ctx.beginPath();
    ctx.moveTo(0, i * gridSize);
    ctx.lineTo(canvas.width, i * gridSize);
    ctx.stroke();

    // 绘制竖线
    ctx.beginPath();
    ctx.moveTo(i * gridSize, 0);
    ctx.lineTo(i * gridSize, canvas.height);
    ctx.stroke();
  }

  // 绘制五个小黑点
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  const points = [
    { x: 3, y: 3 },
    { x: 3, y: boardSize - 4 },
    { x: boardSize - 4, y: 3 },
    { x: boardSize - 4, y: boardSize - 4 },
    { x: 7, y: 7 }, // 正中间的点
  ];

  for (const point of points) {
    drawCircle(point.x * gridSize, point.y * gridSize, 4, 'black');
  }
}

// 绘制棋子
function drawCircle(x, y, radius, color) {
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, 2 * Math.PI);
  ctx.fillStyle = color;
  ctx.fill();
}


drawBoard();


</script>

</body>
</html>

代码解释:

  • canvas 元素: 创建了一个 canvas 元素,并设置了 idwidthheight 属性。
  • getContext('2d'): 获取 2D 渲染上下文。
  • boardSize: 定义棋盘大小,15x15。
  • gridSize: 计算每个格子的大小。
  • drawBoard() 函数: 绘制棋盘格线和五个定位点。
  • drawCircle() 函数: 用于绘制棋子,传入 x, y 坐标、半径和颜色。
  • strokeStylelineWidth: 设置线条颜色和宽度。
  • beginPath()moveTo()lineTo()stroke(): 绘制线条的基本步骤。
  • arc()fillStylefill(): 绘制填充圆的基本步骤。

这段代码会在页面上绘制一个 15x15 的五子棋棋盘,并标出五个定位点。 你可以根据需要修改 boardSizecanvas 的宽高以及颜色等参数。 后续可以添加落子逻辑和游戏规则。

posted @ 2024-12-13 11:48  王铁柱6  阅读(62)  评论(0)    收藏  举报