16

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?

miken32
  • 42,008
  • 16
  • 111
  • 154
Jay Mayu
  • 17,023
  • 32
  • 114
  • 148

4 Answers4

30

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>
TylerH
  • 20,799
  • 66
  • 75
  • 101
John Mayer
  • 1,039
  • 1
  • 11
  • 17
  • How would I use this to create a 8 by 6 table? –  May 25 '14 at 06: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 Jan 09 '23 at 12:22
1

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>
Pete21
  • 102
  • 11
0
// 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();
Dinesh
  • 17
  • 1
  • 2
    This needs more information on how it is useful. Code-only answers are seldom of value on Stack Overflow. – TylerH Aug 30 '22 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>
miken32
  • 42,008
  • 16
  • 111
  • 154
  • Is this an answer or an attempt to comment under Dinesh' answer? What does this provide that is new compared to Dinesh' answer? – TylerH Aug 30 '22 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 Aug 30 '22 at 19:40