js实现方格
使用Canvas绘制方格
在HTML中创建Canvas元素,通过JavaScript绘制方格:
<canvas id="gridCanvas" width="400" height="400"></canvas>
const canvas = document.getElementById('gridCanvas');
const ctx = canvas.getContext('2d');
const gridSize = 20; // 每个方格的大小
const lineColor = '#ccc';
// 绘制垂直线
for (let x = 0; x <= canvas.width; x += gridSize) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.strokeStyle = lineColor;
ctx.stroke();
}
// 绘制水平线
for (let y = 0; y <= canvas.height; y += gridSize) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.strokeStyle = lineColor;
ctx.stroke();
}
使用CSS Grid创建方格
通过纯CSS实现方格布局:
<div class="grid-container"></div>
.grid-container {
display: grid;
grid-template-columns: repeat(10, 40px);
grid-template-rows: repeat(10, 40px);
gap: 1px;
background-color: #ddd;
}
.grid-item {
background-color: white;
}
const container = document.querySelector('.grid-container');
for (let i = 0; i < 100; i++) {
const div = document.createElement('div');
div.classList.add('grid-item');
container.appendChild(div);
}
使用SVG绘制方格
通过SVG矢量图形创建可缩放的方格:
<svg id="gridSVG" width="400" height="400"></svg>
const svg = document.getElementById('gridSVG');
const gridSize = 20;
const lineColor = '#999';
// 创建垂直线
for (let x = 0; x <= 400; x += gridSize) {
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x);
line.setAttribute('y1', 0);
line.setAttribute('x2', x);
line.setAttribute('y2', 400);
line.setAttribute('stroke', lineColor);
svg.appendChild(line);
}
// 创建水平线
for (let y = 0; y <= 400; y += gridSize) {
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', 0);
line.setAttribute('y1', y);
line.setAttribute('x2', 400);
line.setAttribute('y2', y);
line.setAttribute('stroke', lineColor);
svg.appendChild(line);
}
使用HTML表格创建方格
通过传统表格实现简单方格:

<table id="gridTable"></table>
const table = document.getElementById('gridTable');
const rows = 8;
const cols = 8;
for (let i = 0; i < rows; i++) {
const tr = document.createElement('tr');
for (let j = 0; j < cols; j++) {
const td = document.createElement('td');
td.style.width = '50px';
td.style.height = '50px';
td.style.border = '1px solid #000';
tr.appendChild(td);
}
table.appendChild(tr);
}






