lørdag den 26. marts 2011

A simple HTML5 Canvas bouncing dots javascript code

function canvas(canvas_id){
this.x=10;
this.y=10;
this.dx = Math.ceil(Math.random()*10);
this.dy = Math.ceil(Math.random()*10);
this.w=30;
this.h=30;
this.id= canvas_id;
this.cvs;
this.cvsHeight;
this.cvsWidth;
this.ctx;

this.init = function(){
this.x=Math.ceil(Math.random()) * 2;
this.y=Math.ceil(Math.random()) * 2;
this.cvs = document.getElementById("playground");
this.cvsHeight = parseInt( this.cvs.height );
this.cvsWidth = parseInt( this.cvs.width );
this.ctx = this.cvs.getContext('2d');
}

this.draw = function(){
//this.ctx.fillStyle="rgb(00,00,00)";
this.ctx.fillStyle=this.randomColor();
this.ctx.strokeStyle = "rgb(255,255,255)";
this.ctx.fillRect(this.x,this.y,this.w,this.h);
this.ctx.strokeWidht=2;
this.ctx.strokeRect(this.x,this.y,this.w,this.h);
}

this.move = function(){
this.x += this.dx;
this.y += this.dy;

if(this.x + this.w >= this.cvsWidth || this.x <= 0){
this.dx = this.dx*-1;
}

if(this.y + this.h >= this.cvsHeight || this.y <= 0){
this.dy = this.dy*-1;
}
}

this.clear = function(){
this.ctx.clearRect(0,0,this.cvsWidth,this.cvsHeight);
}

this.randomColor = function(){
var color = "#";
for( var i = 0; i < 6; i++ ) color += "0123456789ABCDEF"[Math.round(Math.random()*14)];
return color;
}

}

var c;

var a = [];

function run(){

a[0].clear();

for( var i = 0 ; i < a.length ; i++ ){
a[i].draw();
a[i].move();
}

}

function myonload(){
for( var i = 0 ; i < 5 ; i++ ){
a[i] = new canvas('playground');
a[i].init();
}
setInterval( "run()" , 10 );
}

0 kommentarer:

Send en kommentar