Created
May 7, 2013 01:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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