19

I've been searching everywhere and couldn't find how to draw a grid on an HTML5 Canvas. I'm new to HTML5 and canvas.

I know how to draw shapes but this drawing grid is taking forever to understand.

Can someone help me on this?

0

4 Answers 4

32

The answer is taken from here Grid drawn using a <canvas> element looking stretched

Just edited it a little, hope it helps

// 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>

2
  • How would I use this to create a 8 by 6 table?
    – user3011902
    Commented May 25, 2014 at 6:07
  • This will lag massively if you try to draw a grid every frame, because context.moveTo/lineTo appends to current path without clearing it. If you would want to call drawBoard() every frame, remember to clear a path using ctx.beginPath()
    – Tooster
    Commented Jan 9, 2023 at 12:22
2

I know this question was already answered, but I made my own method that works very similar to the context.fillRect() function, and you can change the grid cell size.

(Change "ctx" to your context variable name, and change the color of the stroke style to whatever you want.)

Here is the working example:

/**
 * @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

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Box width
var bw = 270;
// Box height
var bh = 180;

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();
<canvas id="canvas" width="800" height="600"></canvas>

1
  • 3
    This needs more information on how it is useful. Code-only answers are seldom of value on Stack Overflow.
    – TylerH
    Commented Aug 30, 2022 at 19:31
-1

This code allows for a scalable / resize grid

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>

2
  • Is this an answer or an attempt to comment under Dinesh' answer? What does this provide that is new compared to Dinesh' answer?
    – TylerH
    Commented Aug 30, 2022 at 19:30
  • @TylerH I just removed the reference to the other answer. It wasn't adding anything and this code seems pretty different from it.
    – miken32
    Commented Aug 30, 2022 at 19:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.