// 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 < 10; i++) {
var x = Math.random()*250;
var y = Math.random()*250+50;
var width = height = Math.random()*30;
// 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, put it back
if(tmpShape.x > 500) {
tmpShape.x = 0;
reborn(tmpShape);
};
// we don't use < 0 because the shape must be first "unvisible"
//...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.