Learn how to make a dynamic grid with changing colors
If you want to create an 8x8 grid filled with randomly colored rectangles, you can use the following code snippet:
var n=parseInt(Math.random()*64);
var r=parseInt(n/8);
var c=n-r*8;
ctx.fillStyle=randomColor();
ctx.fillRect(c*20,r*20,20,20);
To generate a random color, you can implement this function:
function randomColor(){
return("#"+Math.floor(Math.random()*16777215).toString(16));
}
Simply add an animation loop to bring your grid to life!
You can find the code and a live demo on http://jsfiddle.net/m1erickson/n2ymp/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var fps = 30;
function animate() {
setTimeout(function() {
requestAnimFrame(animate);
// Drawing code goes here
var n=parseInt(Math.random()*64);
var r=parseInt(n/8);
var c=n-r*8;
ctx.fillStyle=randomColor();
ctx.fillRect(c*20,r*20,20,20);
}, 1000 / fps);
}
// create a random color object {red,green,blue}
function randomColor(){
return("#"+Math.floor(Math.random()*16777215).toString(16));
}
animate();
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=600 height=400></canvas>
</body>
</html>