js实现方格
以下是JavaScript实现方格效果的几种常见方法,涵盖基础绘制、动态交互及样式控制:
使用HTML5 Canvas绘制方格
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = 400;
canvas.height = 400;
// 方格参数
const gridSize = 20;
const rows = canvas.height / gridSize;
const cols = canvas.width / gridSize;
// 绘制方格
ctx.strokeStyle = '#ccc';
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
ctx.strokeRect(j * gridSize, i * gridSize, gridSize, gridSize);
}
}
使用CSS Grid生成方格
通过DOM动态创建方格元素并应用CSS Grid布局:

const container = document.createElement('div');
document.body.appendChild(container);
container.style.display = 'grid';
container.style.gridTemplateColumns = 'repeat(10, 30px)';
container.style.gap = '1px';
// 创建方格元素
for (let i = 0; i < 100; i++) {
const cell = document.createElement('div');
cell.style.backgroundColor = '#eee';
cell.style.height = '30px';
container.appendChild(cell);
}
动态交互方格(点击变色)
结合事件监听实现交互效果:

const container = document.createElement('div');
container.style.display = 'flex';
container.style.flexWrap = 'wrap';
container.style.width = '300px';
for (let i = 0; i < 100; i++) {
const cell = document.createElement('div');
cell.style.width = '30px';
cell.style.height = '30px';
cell.style.border = '1px solid #000';
cell.addEventListener('click', () => {
cell.style.backgroundColor = `hsl(${Math.random() * 360}, 70%, 50%)`;
});
container.appendChild(cell);
}
document.body.appendChild(container);
使用SVG绘制方格
通过JavaScript动态生成SVG方格:
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '200');
svg.setAttribute('height', '200');
document.body.appendChild(svg);
const gridSize = 20;
for (let x = 0; x < 200; x += gridSize) {
for (let y = 0; y < 200; y += gridSize) {
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', x);
rect.setAttribute('y', y);
rect.setAttribute('width', gridSize);
rect.setAttribute('height', gridSize);
rect.setAttribute('stroke', '#999');
rect.setAttribute('fill', 'transparent');
svg.appendChild(rect);
}
}
性能优化建议
对于大规模方格渲染(如游戏地图),建议使用Canvas或WebGL。若需DOM操作,可采用文档片段(DocumentFragment)减少重绘:
const fragment = document.createDocumentFragment();
for (let i = 0; i < 1000; i++) {
const cell = document.createElement('div');
// 设置样式...
fragment.appendChild(cell);
}
document.body.appendChild(fragment);
根据具体需求选择合适的方法,Canvas适合复杂图形,DOM/CSS方案更适合需要动态样式的场景。






