使用canvas画一个中国象棋的棋盘

<!DOCTYPE html>
<html>
<head>
<title>中国象棋棋盘</title>
<style>
canvas {
  background-color: #f0d9b5; /* 象棋棋盘背景色 */
  display: block;
  margin: 20px auto;
}
</style>
</head>
<body>

<canvas id="chessboard" width="450" height="500"></canvas>

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

const gridSize = 50; // 格子大小
const boardWidth = 9 * gridSize; // 棋盘宽度
const boardHeight = 10 * gridSize; // 棋盘高度

// 绘制棋盘
function drawBoard() {
  ctx.lineWidth = 2;
  ctx.strokeStyle = '#000';

  for (let i = 0; i < 10; i++) {
    ctx.beginPath();
    ctx.moveTo(0, i * gridSize);
    ctx.lineTo(boardWidth, i * gridSize);
    ctx.stroke();
  }

  for (let i = 0; i < 9; i++) {
    ctx.beginPath();
    ctx.moveTo(i * gridSize, 0);
    ctx.lineTo(i * gridSize, boardHeight);
    ctx.stroke();
  }

  // 绘制“楚河汉界”
  ctx.font = '20px Arial';
  ctx.textAlign = 'center';
  ctx.fillText('楚河', gridSize * 1.5, gridSize * 4.5);
  ctx.fillText('汉界', gridSize * 7.5, gridSize * 4.5);


  // 绘制斜线 (炮和兵的移动范围)
  function drawSlant(x1, y1, x2, y2) {
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      ctx.stroke();
  }

  for (let i of [0, 2, 4, 6, 8]) {
      drawSlant(i * gridSize, 0, (i + 1) * gridSize, gridSize);
      drawSlant(i * gridSize, gridSize * 2, (i + 1) * gridSize, gridSize * 3);
      drawSlant(i * gridSize, boardHeight - gridSize * 2, (i + 1) * gridSize, boardHeight - gridSize);
      drawSlant(i * gridSize, boardHeight - gridSize, (i + 1) * gridSize, boardHeight);
  }

  for (let i of [1, 3, 5, 7]) {
      drawSlant((i + 1) * gridSize, 0, i * gridSize, gridSize);
      drawSlant((i + 1) * gridSize, gridSize * 2, i * gridSize, gridSize * 3);
      drawSlant((i + 1) * gridSize, boardHeight - gridSize * 2, i * gridSize, boardHeight - gridSize);
      drawSlant((i + 1) * gridSize, boardHeight - gridSize, i * gridSize, boardHeight);
  }
}

drawBoard();
</script>

</body>
</html>

关键改进:

  • "楚河汉界" 文字绘制: 使用了 fillText 方法绘制文字,并设置了字体大小和对齐方式。
  • 斜线绘制: 添加了 drawSlant 函数来绘制斜线,使棋盘更完整。
  • 背景颜色: 设置了棋盘的背景颜色,使其更美观。
  • 代码结构: 使用了函数封装绘制逻辑,使代码更清晰易懂。

这个改进后的代码会绘制一个更完整的中国象棋棋盘,包括棋盘线、"楚河汉界"文字以及炮和兵的移动斜线。 你可以根据需要进一步修改样式和添加棋子。

posted @ 2024-12-14 06:01  王铁柱6  阅读(52)  评论(0)    收藏  举报