Skip to content

Instantly share code, notes, and snippets.

@macloo
Created April 11, 2013 14:52
Show Gist options
  • Save macloo/5364032 to your computer and use it in GitHub Desktop.
Save macloo/5364032 to your computer and use it in GitHub Desktop.
A CodePen by Mindy McAdams. Canvas and setInterval - Create a grid of squares that all change color endlessly, on a 500ms timer.
<canvas id="myCanvas" width="600" height="320">
<p>Some default content can appear here.</p>
</canvas>
window.onload = setInterval(draw, 500);
// Above:
// repeatedly runs the function named "draw" because of setInterval
// 500 means 500 milliseconds, or run it twice every second
function draw() {
var canvas = document.getElementById('myCanvas'); // canvas with id="myCanvas"
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
//------------------------------------
for (var i = 0; i < 5; i++) {
for (var j = 0; j < 12; j++) {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
// above: generate random numbers for each value
ctx.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
ctx.fillRect(j*50, i*50, 50, 50); // create one square
}
}
//------------------------------------
}; // close "if"
} // close draw()
body { padding: 10px; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment