arrays in js

by soggydoughnut54

HTML

<canvas width="500" height="500" id="myCanvas"></canvas>
<p id="p">
Hey
</p>

CSS

#myCanvas {
    border:1px solid #000;
}

JavaScript

/*************
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);