13 - Drawing a Starfield (Part 2)

Now for the next step, how to make a 3D Starfield on your canvas.

PART TWO


A 3D starfield is quite an easy thing to create using CODEF. To make it even easier, there is even a simple library specifically for this purpose. 

Add the following line into your SCRIPT code section, after the main CODEF_CORE.JS call.


<script src="http://codef.namwollem.co.uk/JS/CODEF/codef_starfield.js"></script>

That will bring the script into play, and next we start to define the starfield we want, give it properties, and finally draw it onto your canvas.
After you have defined your canvas in your case, you need to define the starfield.

var mystarfield;

Next, in the INIT section, we set up some parameters.


mystarfield=new starfield3D(mycanvas,500,2,640,480,320,240,'#FFFFFF',100,0,0);

This defines a 3D starfield, applies it to the canvas of choice (in this case, "mycanvas"), and then the following settings are used. In this example we are calling 500 stars, 2 pixels by 2 pixels in size (when at the front of the canvas), and then the starfield is calculated across the size of the canvas (in this case 640 by 480), then we define the position of the centre of the starfield (320 by 240). Next up the colour of the stars is defined - in this case WHITE (#FFFFFF), then 100 is the "bit depth" - visible movement range, followed by 0 (zero) and 0 (zero).
(To be honest I have no idea what the last two zeroes do, so I always leave them alone!)


Finally, we call the command to draw the starfield on the canvas in the GO section of the code.

mystarfield.draw();

You can see the entire script and HTML below, and see it in action here.



<!DOCTYPE HTML>
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>TEST</title> 

<script src="http://codef.namwollem.co.uk/JS/CODEF/codef_core.js"></script> 
<script src="http://codef.namwollem.co.uk/JS/CODEF/codef_starfield.js"></script>

<script> 

var mycanvas;

var mystarfield;

function init(){
mycanvas=new canvas(640,480,"main");

mystarfield=new starfield3D(mycanvas,500,2,640,480,320,240,'#FFFFFF',100,0,0);

go();
}

function go(){
mycanvas.fill('#000000');

mystarfield.draw();

requestAnimFrame( go );
}

</script>

</head> 
<body onLoad="init();">
<body bgcolor="#FFFFFF">
<br>
<center>
<div id="main"></div><br><br>
<a href="javascript:window.location='view-source:'+window.location">View Source</a>
</center>
</body> 


</html>

No comments:

Post a comment