在HTML5的画布元素上绘制一个网格。

17

我已经到处搜索,但找不到如何在HTML5画布上绘制网格的方法。我是HTML5和canvas的新手。

我知道如何绘制形状,但这个绘制网格让我感到很困惑。

有人可以帮助我吗?

4个回答

30
从这里获取答案 使用<canvas>元素绘制的网格看起来被拉伸了
我只是稍微编辑了一下,希望可以帮到你。

// Box width
var bw = 400;
// Box height
var bh = 400;
// Padding
var p = 10;

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function drawBoard(){
    for (var x = 0; x <= bw; x += 40) {
        context.moveTo(0.5 + x + p, p);
        context.lineTo(0.5 + x + p, bh + p);
    }

    for (var x = 0; x <= bh; x += 40) {
        context.moveTo(p, 0.5 + x + p);
        context.lineTo(bw + p, 0.5 + x + p);
    }
    context.strokeStyle = "black";
    context.stroke();
}

drawBoard();
body {
    background: lightblue;
}
#canvas {
    background: #fff;
    margin: 20px;
}
<div>
    <canvas id="canvas" width="420px" height="420px"></canvas>
</div>


我该如何使用这个来创建一个8行6列的表格? - user3011902
如果您尝试在每一帧绘制网格,这将会导致严重的延迟,因为 context.moveTo/lineTo 会在不清除当前路径的情况下附加到当前路径。如果您想要在每一帧调用 drawBoard(),请记得使用 ctx.beginPath() 清除路径。 - Tooster

1
我知道这个问题已经有人回答过了,但是我自己制作了一个非常类似于context.fillRect()函数的方法,并且你可以改变网格单元的大小。
(将"ctx"更改为你的上下文变量名称,并将描边样式的颜色更改为你想要的任何颜色。)
这是一个可工作的示例:

/**
 * @type { HTMLCanvasElement }
 */
var scene = document.getElementById("scene");
var ctx = scene.getContext("2d");

scene.width = window.innerWidth;
scene.height = window.innerHeight;

var r = 125;
var g = 175;
var b = 150;

var theta = 0;

function drawGrid(x, y, width, height, gridCellSize, color, lineWidth = 1) {
  ctx.save();
  ctx.beginPath();
  ctx.lineWidth = lineWidth;
  ctx.strokeStyle = color;

  for (var lx = x; lx <= x + width; lx += gridCellSize) {
    ctx.moveTo(lx, y);
    ctx.lineTo(lx, y + height);
  }

  for (var ly = y; ly <= y + height; ly += gridCellSize) {
    ctx.moveTo(x, ly);
    this.ctx.lineTo(x + width, ly);
  }

  ctx.stroke();
  ctx.closePath();
  ctx.restore();
}

function main() {
  r += Math.sin(theta / 32);
  g += Math.sin(theta / 8);
  b += Math.sin(theta / 16);

  r %= 255;
  g %= 255;
  b %= 255;
  ctx.clearRect(0, 0, scene.width, scene.height);
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, scene.width, scene.height);

  drawGrid(0, 0, scene.width, scene.height, scene.height / 8, `rgb(${r}, ${g}, ${b})`, 1);

  theta++;
  requestAnimationFrame(main);
}

main();
*,
*:before,
*:after {
  font-family: roboto, Arial, Helvetica, sans-serif, system-ui, 'Courier New', Courier, monospace;
  padding: 0px 0px;
  margin: 0px 0px;
  box-sizing: border-box;
}

#scene {
  display: block;
  /*filter: brightness(100%);*/
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grid</title>
</head>

<body>
  <canvas id="scene"></canvas>
</body>

</html>


1
// Box width
var bw = 270;
// Box height
var bh = 180;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
function drawBoard(){
    context.lineWidth = 10;
    context.strokeStyle = "rgb(2,7,159)";
    for (var x = 0; x < bw; x += 90) {
        for (var y = 0; y < bh; y += 90) {
           context.strokeRect(x+10, y+10, 90, 90); 
        }
    }
}
drawBoard();

2
这需要更多关于它如何有用的信息。仅有代码的答案在 Stack Overflow 上很少有价值。 - TylerH

-1

这段代码允许可伸缩/调整大小的网格

const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')
canvas.width = window.innerWidth
canvas.height = window.innerHeight      
function drawBoard()
{   
  // canvas dims
  const bw = window.innerWidth
  const bh = window.innerHeight
  const lw = 1              // box border
  const boxRow = 10         // how many boxes
  const box = bw / boxRow   // box size
  ctx.lineWidth = lw
  ctx.strokeStyle = 'rgb(2,7,159)'
  for (let x=0;x<bw;x+=box)
  {
    for (let y=0;y<bh;y+=box)
    {
      ctx.strokeRect(x,y,box,box)
    }
  }
}
let rTimeout = null
window.addEventListener('resize', (e) => 
{
  clearTimeout(rTimeout)
  ctx.clearRect(0, 0, window.innerWidth, window.innerHeight)
  rTimeout = setTimeout(function(){drawBoard()}, 33)
})
drawBoard()
<canvas id="canvas"></canvas>


这是回答还是在Dinesh的回答下尝试评论?相比Dinesh的回答,它提供了什么新东西? - TylerH
@TylerH 我刚刚删除了对另一个答案的引用。它没有添加任何内容,而且这段代码似乎与它非常不同。 - miken32

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接