Drawing a Grid on HTML5 Canvas

Drawing a Grid on HTML5 Canvas

If you wanna draw a Grid as below in the image then following code snippet will help you.

HTML5 Grid drawn on Canvas

var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
				
//setting grid color
context.strokeStyle = "rgb(255, 0, 0)";
				
//drawding grid
for(x=0; x<5; x++){
 for(y=0; y<5; y++){
  context.strokeRect(y*20, x*20, 20, 20);
 }
}

You may want to track on which square the user clicked in the grid. For that use the snippet below. I've used jQuery to reference canvas and to catch the click event.

$("#myCanvas").click(function(e){
 var x = Math.floor((e.pageX-$("#myCanvas").offset().left) / 20);
 var y = Math.floor((e.pageY-$("#myCanvas").offset().top) / 20);
 context.fillStyle = "rgb(0,0,0)";
 context.fillRect(x*20, y*20, 20, 20);
});

Hope it helps you in some way. Good luck.

Did you enjoy this article?
Signup today and receive free updates straight in your inbox. We will never share or sell your email address.

1 Comment

  1. very nice :)

    Reply

Leave a Reply