If you wanna draw a Grid as below in the image then following code snippet will help you.
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.
Subscribe to our mailing list
Subscribe to our mailing list and receive a free udpates
yash says
very nice 🙂