使用canvas创建无限网格可以通过以下步骤实现:
<canvas id="gridCanvas"></canvas>
const canvas = document.getElementById('gridCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function drawGrid() {
const gridSize = 50; // 网格大小
const gridColor = '#ccc'; // 网格颜色
ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
// 绘制垂直线
for (let x = 0; x < canvas.width; x += gridSize) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.strokeStyle = gridColor;
ctx.stroke();
}
// 绘制水平线
for (let y = 0; y < canvas.height; y += gridSize) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(canvas.width, y);
ctx.strokeStyle = gridColor;
ctx.stroke();
}
}
drawGrid();
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawGrid();
});
这样就可以使用canvas创建一个无限网格了。网格的大小和颜色可以根据实际需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云