Skip to content

Instantly share code, notes, and snippets.

@seanghay
Last active February 20, 2022 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanghay/280efa37b13e28f3d72ac662a2fd507e to your computer and use it in GitHub Desktop.
Save seanghay/280efa37b13e28f3d72ac662a2fd507e to your computer and use it in GitHub Desktop.
Draw Grid with Gap on Canvas
// canvas size
const w = 512;
const h = 512;

const columnSize = 6;
const rowSize = 6;
const gap = 10;

const itemWidth = (w + gap) / columnSize
const itemHeight = (h + gap) / rowSize;

for (let col = 0; col < columnSize; col++) {
  for (let row = 0; row < rowSize; row++) {
    ctx.save();
    ctx.fillStyle = randomColor();
    ctx.fillRect(
      itemWidth * col, 
      itemHeight * row, 
      itemWidth - gap, 
      itemHeight - gap
    );
    ctx.restore();  
  }
}

Result

// canvas size
const w = 512;
const h = 512;
const columnSize = 6;
const rowSize = 6;
const gap = 10;
const itemWidth = (w - gap) / columnSize
const itemHeight = (h - gap) / rowSize;
for (let col = 0; col < columnSize; col++) {
for (let row = 0; row < rowSize; row++) {
ctx.save();
ctx.fillStyle = randomColor();
ctx.fillRect(
itemWidth * col + gap,
itemHeight * row + gap,
itemWidth - gap,
itemHeight - gap
);
ctx.restore();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment