Skip to content

Instantly share code, notes, and snippets.

@unisys12
Created May 7, 2013 01:46
Show Gist options
  • Save unisys12/5529719 to your computer and use it in GitHub Desktop.
Save unisys12/5529719 to your computer and use it in GitHub Desktop.
Function that draws a grid on your HTML5 Canvas. To use, just pass the function and a integer, which represents the spacing of the grid in pixels.
function circle(){
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
x = 115;
y = canvas.height / 2;
radius = 95;
counterClockwise = false;
// Create the Circle
ctx.beginPath();
ctx.arc(x, y, radius, 2 * Math.PI, counterClockwise);
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.closePath();
// Create the center dot
ctx.beginPath();
ctx.arc(x, y, 2, 2 * Math.PI, counterClockwise);
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.closePath();
// Create the outer dot
ctx.beginPath();
ctx.arc(20, 130, 2, 2 * Math.PI, counterClockwise);
ctx.fillStyle = "red";
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.stroke();
ctx.closePath();
}
circle();
drawGrid(20); // This uses the above function to draw a grid spaced 20px
function drawGrid(increment){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var height = canvas.clientHeight;
var width = canvas.clientWidth;
var inc = increment;
for (var h = 0; h < width; h++) {
if(h % inc === 0){
ctx.beginPath();
ctx.moveTo(h, 0);
ctx.lineTo(h, height);
ctx.closePath();
ctx.strokeStyle = "rgba(0,0,0,.2)";
ctx.stroke();
}
}
for (var l = inc; l < width; l++) {
if(l % inc === 0){
ctx.beginPath();
ctx.moveTo(0, l);
ctx.lineTo(width, l);
ctx.closePath();
ctx.stroke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment