HTML5 Canvas - 3D Spaceflight example

HTML5 Canvas – 3D Spaceflight example

Today I wanted to know a bit more about the canvas feature and decided to create some examples. So this is my first one. I am pretty impressed how powerful and easy to use canvas are.

IE is not supported

html:

<canvas id="canvas" width="800" height="400">IE is not supported</canvas>

javascript:

var Space = {
    
    canvas: canvas = document.getElementById('canvas'),
    backgroundColor:"rgb(0,0,0)",
    numberOfPoints:2000,
    pixelPerInterval: 4,
    renderInterval:50,
    zAxis: 400,
    points:[],
    
    init: function(){
        
        
        var xCenter = this.canvas.width/2,
            yCenter = this.canvas.height/2;
        
        for (i=0; i<this.numberOfPoints; i++)
	{
		var point3d = [(Math.random()*this.canvas.width) - xCenter, (Math.random()*this.canvas.height) - yCenter , (Math.random()*this.zAxis)-this.zAxis/2 ];
		this.points.push(point3d); 
	}
        
        var self=this;
        self.loop = setInterval(function(){
            self.render();
        }, this.renderInterval);

    }, 
    
    render: function(){
        var c = this.canvas.getContext('2d');
        
        
	c.fillStyle=this.backgroundColor;
  	c.fillRect(0,0, this.canvas.width, this.canvas.height);
  	
	for (i=0; i<this.points.length; i++)
	{
            var point3d = this.points[i]; 

            var x3d = point3d[0],
                y3d = point3d[1],
                z3d = point3d[2]; 

            z3d-=this.pixelPerInterval; 
            
            
            
            if(z3d<-(this.zAxis/2)) z3d +=this.zAxis; 
            point3d[2] = z3d;


            // draw point on 2s canvas
            var scale = (this.zAxis/2)/((this.zAxis/2)+z3d); 
            
            var x2d = (x3d * scale) + this.canvas.width/2;	
            var y2d = (y3d * scale)  + this.canvas.height/2;


            c.lineWidth= scale; 
            c.fillStyle=c.strokeStyle = "rgb("+Math.floor(Math.random()*256)+",255,255)"; 	
            c.beginPath();
            c.moveTo(x2d,y2d); 
            c.lineTo(x2d+scale,y2d);
            c.stroke();
            
  
  
	}
    }    
    
};

Space.init();