Canvas multiple reborn color
HTML
<canvas id="canvas" width="1024" height="800" style="border:1px solid #000000;"></canvas>
JavaScript
// get the theory behind:
// http://nepraunig.com/wp/?p=150
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// the shape object is a placeholder for all squares
// we are going to create
var Shape = function(x, y, width, height, xspeed, yspeed, color) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.xspeed = xspeed;
this.yspeed = yspeed;
this.color = color;
};
// lots of random color functions here:
/* http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript */
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
// all shapes will be stored in an array
// so they can be accessed easily
var shapes = new Array();
// creating 10 shapes with different x, y values,
// width and height and speed for x and y
for (var i = 0; i < 500; i++) {
var x = Math.random() * 250;
var y = Math.random() * 250 + 50;
var width = height = Math.random() * 30 + 5;
// now are also negative values possible
var xspeed = Math.random() * 5 - 2.5;
var yspeed = Math.random() * 5 - 2.5;
var color = get_random_color();
shapes.push(new Shape(x, y, width, height, xspeed, yspeed, color));
};
function animate() {
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
// loop through all the shapes and manipulate their x-values
var shapesLength = shapes.length;
for (var i = 0; i < shapesLength; i++) {
var tmpShape = shapes[i];
tmpShape.x += tmpShape.xspeed;
tmpShape.y += tmpShape.yspeed;
// if one shape leaves the canvas - it will be "reborn"
// which means the size and the x- and y-speed values
// will be recalculated
// if one shape leaves the canvas, put it back
if (tmpShape.x > 10000) {
tmpShape.x = 0;
reborn(tmpShape);
};
// we don't...