Skip to content

Instantly share code, notes, and snippets.

@mimshwright
Created December 9, 2011 00:21
Show Gist options
  • Select an option

  • Save mimshwright/1449417 to your computer and use it in GitHub Desktop.

Select an option

Save mimshwright/1449417 to your computer and use it in GitHub Desktop.
Some code to create a grid using the <canvas> tag. Also animates the grid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Grid!</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>
var t = 0;
window.onload = function(){
var canvas = document.getElementById("canvas");
var c = canvas.getContext("2d");
setInterval(function () {
t++;
clearCanvas(canvas);
var stretch = Math.sin(t/5) * 10;
drawGrid (canvas, "#FF00FF", 40, 40 , 20 + stretch, 30 + t);
}, 50);
};
function clearCanvas(canvas) {
var c = canvas.getContext("2d");
c.beginPath();
c.rect(0,0,800,450);
c.fillStyle = "#000000";
c.fill();
}
function drawGrid (canvas, color, xSpacing, ySpacing, xOffset, yOffset, lineWidth) {
var width = parseInt(canvas.getAttribute("width"));
var height = parseInt(canvas.getAttribute("height"));
var c = canvas.getContext("2d");
var x = xOffset % xSpacing || 0;
var y = yOffset % ySpacing || 0;
lineWidth = lineWidth || 1;
c.beginPath();
while (x < width) {
c.moveTo(x,0);
c.lineTo(x,height);
x += xSpacing;
}
while (y < height) {
c.moveTo(0,y);
c.lineTo(width, y);
y += ySpacing;
}
c.lineWidth = lineWidth;
c.strokeStyle = color;
c.stroke();
}
</script>
</head>
<body>
<canvas id="canvas" width="800" height="450" />
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment