Babylon JS 01

This large document has been pieced-together by a chap called Wingnut (in Dec 2013) who is not affiliated with babylon.js or its developers. Mistakes likely! Not guaranteed fresh beyond Dec 2013! This document/package was made primarily for off-line use, and its (re)publishing rights likely fall under the same copyright rules/policies as the original documents and their owners/authors.

Creating A Basic Scene With BabylonJS

In this section, we are going to create a basic 3D scene with BabylonJS.

Babylon JS 01

Final result

You can develop this scene very easily in a few simple steps.

Before you start, be sure to have a WebGL compatible browser.

Step 1 - The Web Part

First of all, create a basic HTML5 web page:

TIP: If you are copy'n'pasting, clicking in the gray areas and then pressing control-a... is a great way to highlight all the text including the leading tabs for proper indenting (then press control-c to copy). Careful. Control-x will temporarily erase the highlighted text, but a control-z or page reload... brings it back.

Then add a canvas element to the scene and a bit of CSS. This canvas is an HTML5 element, which will be used to draw our scene.

Step 2 - The <body> part:

Step 3 - The <head> part.

Here we put our CSS to view the canvas in maximum size:

Now we have an empty web page, ready to display 3D!

Step 4 - The JavaScript Part

(with a little work still happening in the <head> part) :)

The JS part begins with 'including' (importing) the Babylon source files (the framework) within the <head> element of our HTML 5 document:

(If you don't already have those files, you can find them online... here:, and here:

Careful! The newest version of babylon.js and handjs.js might have version numbers in their names. Be sure to rename them once downloaded, or adjust the SRC names (and possibly paths) used in your two <script> elements that you used within the <head> of your document.

Then finally, at the end of our web page (AFTER </body>), load the engine and create your 'scene'! A 'scene' is composed of:

Loading the engine... here we go! (the part put after the HTML </body> element, which is included here to show positioning)

Below that... just let your imagination run wild as you create incredible scenes like this one:

And you are already done! Just for kicks, make sure you don't have two </body> or two </html> elements.

The full document should look like this...

Now, you should see your sphere in 3D within your webGL-ready browser.

Don't hesitate to download the complete source code HERE.

02 Basic Elements

In this section, we are going to learn how to create basic elements using Babylon JS such as boxes, spheres, and planes.


Final result

Creating an object is easy, but as for building our future scenes, the code will become more and more complex. So, let's envision a brand new document structure. We still start with a fresh HTML 5 page with our babylon.js and hand.js files being included in the document's <head> just like before. But this time, notice how we are including two more JS files in that section... babylonprep.js and myscene.js You may name these two files per your liking, as we will be MAKING them as seperate documents ourselves. Adjust your two new script elements to reflect whatever names you use for them.

Just like with the hand.js and babylon.js <script> elements, the two new <script> elements are put within the <head> of the HTML 5 document... like so:

For THIS demo, that's all that is needed in the HTML document, so you can save it just like that.

Now let's talk about the two new JS files that we'll be creating:

babylonprep.js file

In a new text editor window... insert the following code and then save it as 'babylonprep.js'. Put it in the same folder/dir as your HTML document for now. Later, you could make a new folder called 'scripts' and put all your JS files into it, adjusting the SRC paths in all your <script> elements. ie. scripts/babylon.js, scripts/hand.js, scripts/babylonprep.js, and scripts/myscene.js

The babylonprep.js file contains all the general re-usable Babylon startup mechanics: loading the engine, testing for WebGL support, scaling the scene to browser size, and obviously loading our scene and rendering it. babylonprep.js won't change a lot in the future as we now have all the basic scene-startup functions in it. It is VERY re-usable.

Put the code below in that fresh text editor window, and save it as 'babylonprep.js'

Easy as pie. Notice how we are wedging into window.onload which runs as soon as our HTML 5 document finishes loading. It 'starts the ball rolling' if you'll pardon my 3D humor. Got that babylonprep.js file saved? Good deal! Well done. Onward to myscene.js... the second of the two new JS files...

myscene.js file

The myscene.js file is all of our created scene. It is about to become our main JS file, where we are going to create all of our objects, lights, cameras, actions. As mentioned in the previous JS file, myscene.js must have a function in it called 'createScene' in order for babylonprep.js to call/use.

As we have learned in the previous section, first, we are creating a basic scene (scene object, camera, light).

In a fresh text editor window... insert the following code, but you don't need to save it until further on.

Still no save is needed. We have not yet created any geometry/models to view. So, now, you can add all the meshes that you like! Let's put an assortment of basic 3D objects/elements into myscene.js now...

Now you have a scene with 5 new objects in it, but the default position of all meshes is vector zero (x=0, y=0, z=0), so how can you move them? Simply by giving them a new 3D point, a 'Vector3'. (Look at this video for a vector tutorial). So if you want to move your box, maybe add this...

You can use similar lines to move the other objects as well and as easily.

We are nearly ready to go. Lastly, return the scene object to the first JS file... and close the function '}' to complete the creation of our scene.

Your ENTIRE myscene.js should look something like this...

If it does... NOW please save myscene.js in the same folder/directory as your HTML file (for now).

And that's it! The HTML page includes-in (loads) four JS files... babylon.js, hand.js, babylonprep.js, and myscene.js. Put your HTML page in a browser, and you should have a tolerable default-textured scene of assorted polygons/geometry. Ready for some fancier things? I knew you were. You'll be working almost exclusively in myscene.js from now on, yet will likely always be using this same five-document structure for all your future projects... simply renaming myscene.js for new projects, and adjusting THAT filename in one of the <script> elements of your HTML page(s). Essentially, the HTML document and the three reusable JS files (babylon.js, hand.js, and babylonprep.js) are a starter kit, and myscene.js will be modified very often. Whenever you change the name of myscene.js, be sure to reflect the new name in the corresponding <script> element in THAT project's HTML launcher page.

NOTE: If you experience errors involving scene.meshes, or if the cylinder refuses to render, make sure you have 7 parameters in the CreateCylinder call, and that you are using babylon.js v1.7 or higher. Earlier versions of babylon.js used only 6 parameters. Babylon.js is continuously evolving, and we like it that way. :)

03 Rotation & Scaling

This time you are going to learn how to move and rotate any kind of objects that you created in our last tutorial.


Final result

For this scene, we won't change anything in the structure: changes are only on the scene file, in the function called 'createScene'. As usual, we are beginning the function by writing basic elements of a scene:

Then create as many boxes as you want:

As we seen earlier, you can now position all the boxes on the scene

And now, with the same ease of coding, you can rotate on all axes, and rescale in any size! For example:

Another Babylon's feature is moving an object, relatively to another by creating a link between two meshes. This link implies that all parent transformations (position/rotation/scaling) will be combined with the child's transformations.

Next step

Now you know how to create and move object on a scene, but all your meshes looks the same way…! Not for long if you read next tutorial about textures. Go to Tuto 04

Download source code HERE

04 Materials

Now that you can create different meshes everywhere in the scene, we are going to give those meshes some materials, to define how a mesh looks like.


Final result

First, as you are now used to, we create a new basic scene in the 'myscene.js' file:

For now, you only have some grey-lighted meshes. To apply a material on it, you have to create a new material object like this:

And apply this material to the object of your choice, e.g.:

Or, do both at once:

"I tested my scene, and nothing changed!"

Exactly, because this material is the default one, you have to customize it as you want. You won't change the mesh itself, but the material. So how can I shape my material to give the perfect look to my object?

To apply some alpha to a material, written in percent (%):

The diffuse is the native color of the object when it is lighted. You can specify a solid color with the 'diffuseColor' property:

Or, you can use a texture:

More About Textures: Make sure you have the correct path to your image (relative or absolute path). Supported image formats include JPG, PNG, JPEG, BMP, etc. (every image format available on your browser). If you want to translate your texture on your mesh, you can use 'uOffset' and 'vOffset'. If you want to repeat/tile an image pattern (e.g. grass texture), you can use 'uScale' and 'vScale':


And if your texture have some alpha, simply specify it:

The emissive is the color produced by the object. You can specify a solid color with the 'emissiveColor' property:

Or, you can use a texture:

See 'More About Textures' section of 'Diffuse'... to learn more about emissiveTexture. Remember to change each occurence of 'diffuse'... to 'emissive', of course.

The ambient can be seen as a second level of diffuse. The produced color is multiplied to the diffuse color. This is especially useful if you want to use light maps baked into textures.. You can specify a solid color with the 'ambientColor' property:

Or, you can use a texture:

See 'More About Textures' section of 'Diffuse'... to learn more about ambientTexture. Remember to change each occurence of 'diffuse'... to 'ambient', of course.

The specular is the color produced by a light reflecting on a surface. You can specify a solid color with the 'specularColor' property:

Or, you can use a texture:

See 'More About Textures' section of 'Diffuse'... to learn more about specularTexture. Remember to change each occurence of 'diffuse'... to 'specular', of course.

The size of the reflection is defined by the 'specularPower' property.

'Back-face culling' determines whether a polygon of a graphical object is visible or not. In short, if active, Babylon engine won't render hidden face of this material. It's true by default, but can be swapped to false if you need to.

In this example, a texture have some alpha, and back-face culling needs to be set to false to see the inside face:


You can see your object in Wireframe by writing:


Next step

Great, your scene is better than ever with those materials! Later we will see how to use advanced techniques with materials, but for now, we have to learn how to use cameras.

Download source code HERE

05 Cameras

To continue building our scene, let's see how to manage cameras.


Final result

Cameras management is pretty simple: Babylon.js supports 3 kind of cameras:

You can create as much cameras as you want but only one camera can be active at a time. Here is how to write the code for each of those cameras:

All the cameras can automatically handle inputs for you by calling 'attachControl' function on the canvas. And you can revoke the control by using 'detachControl' function:

Note that you can change some parameters later, depending of the type of cameras: Change target/position of ArcRotate camera:

Change sensibility of Touch camera:

Apply gravity to Free camera: later in these tutorials ;)

Next step

Now you can control how to see your scene, how to move around your meshes. To give your scene a more realistic effect, we are going to see how to manage lights. See you soon.

Download source code HERE

06 Lights

In the previous section, we discovered how to use materials to define the aspect of your meshes. Now we are ready to talk about lights. Lights are used to produce the diffuse and specular color received by each pixel. This color is then used by materials to determine the final color of every pixel.

Babylon.js allows you to create and register as many lights as you want but beware because the StandardMaterial can handle only 4 simultaneous lights (the first four enabled lights of the lights list)

During this article, I will show you how to use every kind of lights supported by babylon.js.

Activating/Deactivating lights

Every light can be deactivated by setting its isEnabled property to false.

But you can also control the global intensity of the light with the intensity property.

The point light

A point light is a light defined by an unique point. The light is emitted in every direction from this point.

You can control the color of the light with the diffuse and specular properties:

Red diffuse point light with white specular

The directional light

A directional light is defined by a direction (what a surprise!). The light is emitted from everywhere to a specific direction and has an infinite range.

Like a point light, you can control the color of the light with the diffuse and specular properties:

Red diffuse directional light with white specular

The spot light

A spot light is defined by a position, a direction, an angle and an exponent. These values define a cone of light starting from the position toward the direction. The angle defines the size of the spotlight beam and the exponent defines the speed of the decay of the light with distance:

A red diffuse spotlight with white specular and a 0.8 radians wide cone. The exponent value is 2.

The hemispheric light

Hemispheric light represents a simple and easy way to simulate realistic ambient light. An hemispheric light is defined by a direction to the sky and by 3 colors: one for the diffuse (the sky color), one for the ground (the color when the pixel is not towards the sky) and one for the specular.

White/black hemispheric light

What's next?

If you want to go more deeply into babylon.js, here are some useful links: