js实现棋盘
使用HTML和JavaScript创建棋盘
创建一个棋盘可以通过HTML的表格元素结合JavaScript动态生成。以下是实现方法:
<!DOCTYPE html>
<html>
<head>
<title>棋盘</title>
<style>
table {
border-collapse: collapse;
}
td {
width: 50px;
height: 50px;
border: 1px solid black;
}
.black {
background-color: black;
}
.white {
background-color: white;
}
</style>
</head>
<body>
<div id="chessboard"></div>
<script>
function createChessboard(size) {
const board = document.getElementById('chessboard');
const table = document.createElement('table');
for (let i = 0; i < size; i++) {
const row = document.createElement('tr');
for (let j = 0; j < size; j++) {
const cell = document.createElement('td');
cell.className = (i + j) % 2 === 0 ? 'white' : 'black';
row.appendChild(cell);
}
table.appendChild(row);
}
board.appendChild(table);
}
createChessboard(8); // 创建8x8棋盘
</script>
</body>
</html>
使用Canvas绘制棋盘
另一种方法是使用HTML5 Canvas元素绘制棋盘:
<!DOCTYPE html>
<html>
<head>
<title>Canvas棋盘</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="chessCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('chessCanvas');
const ctx = canvas.getContext('2d');
const size = 8; // 8x8棋盘
const cellSize = canvas.width / size;
function drawChessboard() {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
ctx.fillStyle = (i + j) % 2 === 0 ? 'white' : 'black';
ctx.fillRect(j * cellSize, i * cellSize, cellSize, cellSize);
ctx.strokeRect(j * cellSize, i * cellSize, cellSize, cellSize);
}
}
}
drawChessboard();
</script>
</body>
</html>
添加交互功能
可以为棋盘添加点击事件,实现棋子放置功能:
// 在Canvas示例基础上添加
canvas.addEventListener('click', function(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
const col = Math.floor(x / cellSize);
const row = Math.floor(y / cellSize);
// 绘制红色棋子
ctx.beginPath();
ctx.arc(
col * cellSize + cellSize / 2,
row * cellSize + cellSize / 2,
cellSize / 2 - 5,
0,
Math.PI * 2
);
ctx.fillStyle = 'red';
ctx.fill();
ctx.stroke();
});
使用CSS Grid创建棋盘
纯CSS方案结合少量JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>CSS Grid棋盘</title>
<style>
#chessGrid {
display: grid;
grid-template-columns: repeat(8, 50px);
grid-template-rows: repeat(8, 50px);
width: 400px;
height: 400px;
}
.cell {
border: 1px solid black;
}
.black {
background-color: black;
}
.white {
background-color: white;
}
</style>
</head>
<body>
<div id="chessGrid"></div>
<script>
const grid = document.getElementById('chessGrid');
const size = 8;
for (let i = 0; i < size * size; i++) {
const cell = document.createElement('div');
const row = Math.floor(i / size);
const col = i % size;
cell.className = `cell ${(row + col) % 2 === 0 ? 'white' : 'black'}`;
grid.appendChild(cell);
}
</script>
</body>
</html>
这些方法提供了不同技术路线实现棋盘效果,可根据项目需求选择合适方案。表格方法简单直接,Canvas适合需要复杂交互的场景,CSS Grid则展示了现代CSS布局能力。






