/*************
variables to make program work
*************/
//access the canvas
var canvas = document.getElementById('myCanvas');
//access drawing environment
var context = canvas.getContext("2d");
//the array of boxes
var boxes = [];
//make a new box:
new box();
new box();
new box();
//for loop
for(var i = 0; i <200 ; i++){
new box();
}
box[0].color = "white"
box[0].size = 64
/***********
FUNCTION TO DRAW BOXES
*********/
function drawBoxes(){
for(var i = 0; i < boxes.length; i++){
//draw each box using i
boxes[i].draw();
}
}
/***********
function for drawing stuff
************/
function draw() {
//background
context.fillStyle = "black";
context.fillRect(0, 0, 500, 500);
//text formatting
context.fillStyle = "white";
context.font = "20px Arial";
//draw all of the boxes
drawBoxes();
context.fillText("number of boxes : " + boxes.length, 30, 30);
document.getElementById('p').innerHTML = "boxes array:<br/>"+boxes;
}
//makes a box at a random location
function Box(){
this.x = Math.round(Math.random()*450);//random x
this.y = Math.round(Math.random()*300)+150;//random y
this.size = 20;//size
this.dir = Math.round(Math.random())-1;//random dir
if(this.dir===0){
this.dir=1;//set to 1 if it is 0
}
this.spd = Math.random()*10;//random speed
this.color = "red";//color
boxes.push(this);//add to array
}
//tell the box to draw itself
Box.prototype.draw = function(){
context.fillStyle = this.color;
context.fillRect(this.x, this.y, this.size, this.size);
//move the box
this.x+=this.dir*this.spd;
//bounce off walls
if(this.x < 0 || this.x+this.size > 500){
this.dir *=-1;
}
}
/************
Call the function
************/
thread = setInterval(draw, 30);
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.