Babylon.js: a complete JavaScript framework for building 3D games with HTML 5 and WebGL

/ Updated on 4/10/14 to reflect API changes /

I am a real fan of 3D development. Since I was 16, I spent all my spare time creating 3d engines with various technologies (DirectX, OpenGL, Silverlight 5, pure software, etc.).

My happiness was complete when I discovered that Internet Explorer 11 has native support for WebGL. So I decided to write once again a new 3D engine but this time using WebGL and my beloved JavaScript.

If you are a 3D beginner, I suggest you to read this excellent series of blogs written by my friend David Rousset:

Thus babylon.js was born and you can find some samples right here:

You can also find all the sources on Babylon.js Github repository:


All the scenes were created by one of the most talented 3D artist I know: Michel Rousseau who by the magic of the life is also my colleague at Microsoft and has a really cool blog for designers:

The engine is currently at early stage but I plan to add a lot of cool new features quickly.

The current version supports the following features (I always loved this kind of very long and very technical list):

  • Complete scene graph with lights, cameras, materials, sprites, layers and meshes
  • Complete collisions/responses system
  • Highly configurable material with support with
    • Diffuse
    • Specular
    • Emissive
    • Opacity / Alpha
    • Reflection
    • Ambient
    • Bump
    • Up to 4 simultaneous lights
  • Four kind of lights:
    • Point
    • Directional
    • Spot
    • Hemispheric
  • Three kind of cameras:
    • Free camera (FPS like)
    • Touch compatible camera
    • Arc rotate camera
  • Textures:
    • 2D
    • Render target
    • Mirrors
    • Dynamic
    • Video Textures
  • Alpha blending
  • Alpha testing
  • Billboarding / sprites
  • Scene picking
  • Frustum clipping
  • Sub-meshes clipping
  • Antialiasing
  • Particles system
  • Animations engine
  • Fog
  • Babylon file format is a JSON file that can be produced from:
    • .OBJ
    • .FBX
    • .MXB
    • Blender


Obviously I will not cover ALL the features during this article. Indeed this one is just the first one of a long series that will focused on every feature of babylon.js.

You want to discuss about this article: reach me on Twitter: @deltakosh


  1. Getting started with babylon.js
  2. Materials
  3. Lights, cameras and meshes
  4. Collisions
  5. Particle Systems
  6. Spites and layers
  7. Animations
  8. Advanced textures
  9. Importing scene from 3D assets
    1. And much more to come…
    2. Next chapters

Getting started with babylon.js

The only thing you really need to unleash the power of babylon.js is a small js file (less than 200 KB uncompressed). You can find the latest version at the root of the Github repo:

You will also need to include hand.js to your page if you want to seamlessly support touch events:

Once you grabbed this file, you just have to import it in your HTML file and create a canvas (this is where babylon.js will render the scenes)

<!DOCTYPE html>
<html xmlns="">
    <title>Using babylon.js - Test page</title>
    <script src="babylon.js"></script>
        html, body {
            width: 100%;
            height: 100%;
            padding: ;
            margin: ;
            overflow: hidden;
        #renderCanvas {
            width: 100%;
            height: 100%;
    <canvas id="renderCanvas"></canvas>

Babylon.js is built around a main object: the engine. This object will let you create a scene where you will be able to add meshes (the 3D objects), lights, cameras and materials:

    var canvas = document.getElementById("renderCanvas");
    var engine = new BABYLON.Engine(canvas, true);

You may want to test if WebGL is supported on the current browser by using the following code:

    if (BABYLON.Engine.isSupported()) {
        var canvas = document.getElementById("renderCanvas");
        var engine = new BABYLON.Engine(canvas, true);

The engine is the hub between babylon.js and WebGL. It is in charge of sending orders to WebGL and creating internal WebGL related objects.

Once the engine is created, you are able to create the scene:

var scene = new BABYLON.Scene(engine);

The scene can be seen as a container for all entities that works together to create a 3D image. With the scene you can create a light, a camera and a mesh (in this case a sphere):

var camera = new BABYLON.FreeCamera("Camera", new BABYLON.Vector3(0, 0, -10), scene);
var light0 = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(0, 100, 100), scene);
var sphere = BABYLON.Mesh.CreateSphere("Sphere", 16, 3, scene);

Babylon.js supports different kind of cameras, lights and meshes. I will get back to them in this article.

You may have noticed the usage of BABYLON.Vector3 to define a 3D position. Indeed, babylon.js comes with a complete math Library that can handle vectors, matrix, colors, rays and quaternions.

Please note that babylon.js use a left handed coordinate system:


The last thing you need to do is to register a render loop:

// Render loop
var renderLoop = function () {
    // Start new frame


    // Present

    // Register new frame


Using QueueNewFrame (which is just a call to requestAnimationFrame when supported or setTimeout else), you will ask the browser to call your renderLoop as soon as possible. The renderLoop itself is based upon 4 parts:

  • engine.beginFrame: This is a required call to determine the start of a new frame
  • scene.render: Asks the scene to render all entities it owns
  • engine.endFrame: Closes the current frame and present it to the canvas
  • QueueNewFrame: Registers a new frame for rendering

To simplify the code you can also use this construct:

// Render loop
var renderLoop = function () {

// Launch render loop

If you want to add a bit more of real-time, you can add function for scene.beforeRender and use it to animate the sphere:

var alpha = 0;
sphere.scaling.x = 0.5;
sphere.scaling.z = 1.5;
scene.beforeRender = function() {
    sphere.rotation.x = alpha;
    sphere.rotation.y = alpha;

    alpha += 0.01;

The result is the following (if your browser does not support WebGL, you will see a wonderful white on white rectangle):


Our sphere is a bit sad with its simple gray color. This is time for us to talk about materials. A material for babylon.js is an object that defines how a mesh looks like.

Babylon.js has an object called StandardMaterial which supports the following properties:

  • diffuseColor and diffuseTexture: Define the base color of the mesh

  • ambientColor and ambientTexture: Define the ambient color of the mesh (can be used for light maps for instance)

  • specularColor and specularTexture: Define the specular color of the mesh

  • emissiveColor and emissiveTexture: Define the color emitted by the mesh (the color the object has without light)

  • opacityTexture: Define the transparency of the mesh

  • reflectionTexture: Define the reflection color received by the mesh (can be a texture or a dynamic mirror)

  • bumpTexture: Define the bump level of the mesh on a per-pixel basis. You must provide a normal map picture here.

  • alpha: Define the global transparency of the mesh

color properties define an unique color where texture properties use a bitmap to define colors

So let’s add some color to our sphere:

// Material
var material = new BABYLON.StandardMaterial("default", scene);
material.diffuseTexture = new BABYLON.Texture("kosh.jpg", scene);
material.emissiveColor = new BABYLON.Color3(0.3, 0.3, 0.3);
sphere.material = material;

And the result (once again, with WebGL, it should be white…):

The StandardMaterial is very versatile and there are tons of available combinations. For instance let’s change the texture used by the diffuseTexture with a texture that contains alpha values:

var material = new BABYLON.StandardMaterial("default", scene);
material.diffuseTexture = new BABYLON.Texture("tree.png", scene);
material.diffuseTexture.hasAlpha = true;
material.emissiveColor = new BABYLON.Color3(0.3, 0.3, 0.3);
material.backFaceCulling = false;
sphere.material = material;

And the result:

Please note that in this case, we have to indicate that the texture contains useful alpha values (hasAlpha = true). We also need to deactivate the back face culling system (which remove the faces that are not toward us) to see back faces.

To learn more about materials:

You may also be interested by multi-materials:

Lights, cameras and meshes


Babylon.js lets you create 4 kind of lights:

  • pointLight (like the sun for instance) which emits light in every direction from a specific position
  • directionalLight which emits light from the infinite towards a specific direction
  • spotLight which emits light from a position to a direction Inside a cone
  • hemisphericLight which is a special ambient light based on a direction to determine if the light color comes from the ground or from the sky

Creating them is easy:

var point = new BABYLON.PointLight("point", new BABYLON.Vector3(20, 100, 2), scene);
var directional = new BABYLON.DirectionalLight("directional", new BABYLON.Vector3(1, 1, 0), scene);
var spot = new BABYLON.SpotLight("spot", new BABYLON.Vector3(20, 100, 2), new BABYLON.Vector3(1, 1, 0), 0.8, 1, scene);
var hemi = new BABYLON.HemisphericLight("hemi", new BABYLON.Vector3(0, 1, 0), scene);

You can create as much lights as you want but beware: the StandardMaterial can only take in account up to 4 lights simultaneously.

Lights have three main properties:

  • diffuse: Diffuse color
  • specular: Specular color
  • position / direction

Spot lights also have:

  • angle: Cone angle
  • exponent: Attenuation exponent (1 for linear, 2 for pow2, etc…)

Hemispheric lights have:

  • groundColor: color of the “ground” part of the light (sky color is defined by diffuse property)

To learn more about lights:


Babylon.js supports 3 kind of cameras:

  • freeCamera is a FPS like camera where you control the camera with the cursors keys and the mouse
  • touchCamera is a camera controlled with touch events (it requires hand.js to work)
  • arcRotateCamera is a camera that rotates around a given pivot. It can be controlled with the mouse or touch events (and it also requires hand.js to work)

You can create as much cameras as you want but only one camera can be active at a time

var camera = new BABYLON.ArcRotateCamera("Camera1", 0, 0.8, 10, BABYLON.Vector3.Zero(), scene);
var camera2 = new BABYLON.FreeCamera("Camera2", new BABYLON.Vector3(0, 0, -10), scene);
var camera3 = new BABYLON.TouchCamera("Camera3", new BABYLON.Vector3(0, 0, -10), scene);

scene.activeCamera = camera;

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:




Meshes are the only entities that you can effectively see. They have tons of properties and can be created from basic shapes or from a list of vertices and faces.

Basic shapes are:

  • Cube
  • Sphere
  • Plane
var box = BABYLON.Mesh.CreateBox("Box", 0.8, scene);
var sphere = BABYLON.Mesh.CreateSphere("Sphere", 16, 3, scene);
var plane = BABYLON.Mesh.CreatePlane("plane", 3, scene);

You can also create a mesh from a list of vertices and faces:

var plane = new BABYLON.Mesh(name, scene);

 var indices = [];
 var positions = [];
 var normals = [];
 var uvs = [];

 // Vertices
 var halfSize = size / 2.0;
 positions.push(-halfSize, -halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(0.0, 0.0);

 positions.push(halfSize, -halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(1.0, 0.0);

 positions.push(halfSize, halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(1.0, 1.0);

 positions.push(-halfSize, halfSize, 0);
 normals.push(0, 0, -1.0);
 uvs.push(0.0, 1.0);

 // Indices


 plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind);
 plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind);
 plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind);

 return plane;

You have to create a blank new mesh and call setVerticesData and setIndices.

To define where the mesh is, you can use the position/rotation/scaling properties:

plane.position = new BABYLON.Vector3(0, 7, 0);
plane.rotation.z = 0.1;
plane.scaling.x = 2;

Meshes hierarchy

You can create meshes hierarchies by setting the parent property of a mesh. By doing this you create a link between two meshes. This link implies that all parent transformations (position/rotation/scaling) will be combined with the child’s transformations.

For instance, with the following code:

var box = BABYLON.Mesh.CreateBox("Box", 1.0, scene);
box.position = new BABYLON.Vector3(0, 2, 2);
box.parent = sphere;

You will get the following result (based obviously on the previous scene we created, where I removed the scaling of the sphere for clarity):

Activation and visibility

You can control the visibility and the activation of meshes according to following rules:

  • StandardMaterial can control the opacity of an object with
    • alpha property to control alpha blending (transparency) per mesh
    • alpha channel of the diffuseTexture: this will cause babylon.js to activate alpha testing which means it will discard all pixel with alpha value < 0.5
    • opacityTexture to define alpha blending per pixel (and not for the whole mesh like alpha property)
  • visibility property to control the transparency per mesh directly (without using a material)
  • isVisible property to activate the rendering of the mesh. The mesh is kept into the scene for others operations (collisions, picking, etc.). This property is not transmitted to children
  • setEnabled function to deactivate completely a mesh and all its descendants.


One of the great feature of babylon.js is certainly its complete and really simple to use collisions system. By settings a small set of options, you will be able to reproduce a first person shooter.

There are three levels of options to set. First of all you have to activate the collisions globally on the scene and define the gravity:

 scene.collisionsEnabled = true;
 scene.gravity = new BABYLON.Vector3(0, -9, 0);

Then you have to configure the camera you want to use for collisions:

camera.checkCollisions = true;
camera.applyGravity = true;
camera.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);

The collisions engine considers the camera like an ellipsoid (a kind of capsule). In this case the camera is like a big ellipsoid measuring 1mx2mx1m (the ellipsoid property defines the radius of the ellipsoid).

You can also create a flying camera by not applying gravity.

Finally you have to define which meshes can collide:

plane.checkCollisions = true;
sphere.checkCollisions = true;

The result is the following (use the cursors keys to move and the mouse to change your point of view by clicking and moving it. Beware not to fall off of the ground):

Babylon.js can even handle stairs as you can see in the “Espilit demo” on the main site.

Particle systems

Particle systems are a cool toy when you play with 3D. They can easily add stunning effects on your scene (explosions, impacts, magic effects, etc.).

Creating a particle system is simple as follow:

var particleSystem = new BABYLON.ParticleSystem("particles", 4000, scene);

You have to define the maximum capacity of a particle system to allow babylon.js to create associated WebGL objects. So in this case, there will be no more than 4000 active particles simultaneously.

Particle systems are highly configurable with the help of the following set of properties:

  • particleTexture: Defines the texture associated with every particle
  • minAngularSpeed / maxAngularSpeed: The range of the angular rotation speeds of every particle
  • minSize / maxSize: The range of sizes of every particle
  • minLifeTime / maxLifeTime: The range of lifetimes for every particle
  • minEmitPower / maxEmitPower:: The range of emission powers (emission speed) of every particle
  • minEmitBox / maxEmitBox:: The box from where every particle starts (can be a point if min == max)
  • direction1 / direction2: The range of directions for every particle
  • color1 / color2: The range of colors for every particle
  • colorDead: The color of a dead particle (Babylon.js will interpolate particle’s color to this color)
  • deadAlpha: The alpha of a dead particle (in a same way, babylon.js will interpolate particle’s alpha to finish with this specific alpha)
  • textureMask: A mask used to filter which part of the texture is used for every particle
  • blendMode: Alpha blending mode (_BLENDMODE_ONEONE_ to add current color and particle color or _BLENDMODE_STANDARD_ to blend current color and particle color using particle’s alpha)
  • emitter: A Vector3 to define the position of the particle system. You can also used a mesh here and in this case the particle system will use the mesh position
  • emitRate: How many particles are launched on every frame.
  • manualEmitCount: Specifying a value greater or equal to zero here will disable emitRate. You are then responsible for feeding this value to control the particles count emitted.
  • updateSpeed: The global speed of the system
  • gravity: Graviy applied to particles
  • targetStopDuration: Stops the particle system after a specific duration
  • disposeOnStop: Disposes the particle system on stop (Very useful if you want to create a one shot particle system with a specific targetStopDuration)

Every range values are used to generate a controlled random value for every particle.

You can control a particle system by calling start / stop functions.

That’s a lot of properties, isn’t it ? The best way to understand them is to try all of them on a test scene and play with properties. For instance, the following code:

var particleSystem = new BABYLON.ParticleSystem("particles", 4000, scene);
particleSystem.particleTexture = new BABYLON.Texture("Flare.png", scene);
particleSystem.minAngularSpeed = -0.5;
particleSystem.maxAngularSpeed = 0.5;
particleSystem.minSize = 0.1;
particleSystem.maxSize = 0.5;
particleSystem.minLifeTime = 0.5;
particleSystem.maxLifeTime = 2.0;
particleSystem.minEmitPower = 0.5;
particleSystem.maxEmitPower = 1.0;
particleSystem.emitter = new BABYLON.Vector3(0, 0, 0);
particleSystem.emitRate = 500;
particleSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
particleSystem.minEmitBox = new BABYLON.Vector3(0, 0, 0);
particleSystem.maxEmitBox = new BABYLON.Vector3(0, 0, 0);
particleSystem.direction1 = new BABYLON.Vector3(-1, -1, -1);
particleSystem.direction2 = new BABYLON.Vector3(1, 1, 1);
particleSystem.color1 = new BABYLON.Color4(1, 0, 0, 1);
particleSystem.color2 = new BABYLON.Color4(0, 1, 1, 1);
particleSystem.gravity = new BABYLON.Vector3(0, -5, 0);
particleSystem.disposeOnStop = true;
particleSystem.targetStopDuration = 0;

Sprites and layers

Babylon.js is designed to extract the full power of WebGL for your apps and games. And even if you want to create a 2D game, babylon.js can help you by providing a support for sprites and 2D layers.

Please note than you can also define the billboardMode property of a mesh to align it with the camera to simulate a 2D object: plane.billboardMode = BABYLON.Mesh.BILLBOARDMODE_ALL

A sprite is defined by a texture containing all its animation states:

The current state (the current cell displayed) is defined using the cellIndex property. You can then manipulate it by code or use the playAnimation function to let babylon.js control the cellIndex property.

Sprites working on the same texture are gathered around a SpriteManager to optimize resources usage:

var spriteManager = new BABYLON.SpriteManager("MonsterA", "MonsterARun.png", 100, 64, scene);
for (var index = 0; index < 100; index++) {
    var sprite = new BABYLON.Sprite("toto", spriteManager);
    sprite.position.y = 0;
    sprite.position.z = Math.random() * 10 - 5;
    sprite.position.x = Math.random() * 10 - 5;
    sprite.invertU = (Math.random() < 0.5);

    sprite.playAnimation(0, 9, true, 100);

Please note the usage of invertU for inverting horizontally the texture.


In addition to sprites, babylon.js also supports 2D layers in order to let you add backgrounds or foregrounds:

var background0 = new BABYLON.Layer("back0", "Layer0_0.png", scene);
 var background1 = new BABYLON.Layer("back1", "Layer1_0.png", scene);
 var foreground = new BABYLON.Layer("fore0", "Layer2_0.png", scene, false);

The last boolean defines if the layer is background (or not).



There are two ways of animating properties in babylon.js: You can do it by yourself using JavaScript (see previous samples) or you can use the animations engine.

The animations engine is based on objects called Animation (!!). An Animation is defined by various properties and a collection of keys. Every key represents the value of the Animation at a given time. Once an Animation is created you can add it to the animations property of a given object:

// Animations
var animation = new BABYLON.Animation("anim0", "scaling.x", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, 

var keys = [];
    frame: 0,
    value: 1

    frame: 50,
    value: 0.2

    frame: 100,
    value: 1



Animations can work on types:


They can have various behaviors when they hit their upper limit:

  • Use previous values and increment it (BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE)
  • Restart from initial value (BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE)
  • Keep their final value (BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT)

So using the previous codea and this small line will launch the animation:

scene.beginAnimation(box, 0, 100, true);


Advanced textures

Textures can obviously be based on pictures but you have the opportunity with babylon.js to use Advanced features to generate textures at runtime.

Dynamic textures

A dynamic texture uses a canvas to generate its content.

Creating and affecting a dynamic texture is simple:

var dynamicTexture = new BABYLON.DynamicTexture("dynamic texture", 512, scene, true);
dynamicTexture.hasAlpha = true;
material.diffuseTexture = dynamicTexture;

Once the texture is created, you can updated it when you want (for instance here every time the scene is rendered) using the getContext and update functions:

var count = 0;
scene.beforeRender = function() {
    // Dynamic
    var textureContext = dynamicTexture.getContext();
    var size = dynamicTexture.getSize();
    var text = count.toString();;
    textureContext.fillStyle = "red";
    textureContext.fillRect(0, 0, size.width, size.height);

    textureContext.font = "bold 120px Calibri";
    var textSize = textureContext.measureText(text);
    textureContext.fillStyle = "white";
    textureContext.fillText(text, (size.width - textSize.width) / 2, (size.height - 120) / 2);




The getContext returns a true canvas’ context so everything you can do with a canvas is available with a dynamic texture.

Video textures

You can also create textures that use video as content source:

var ecran = scene.getMeshByName("Ecran");
ecran.material.diffuseTexture = new BABYLON.VideoTexture("video", 
["Scenes/Flat2009/babylonjs.mp4", "Scenes/Flat2009/babylonjs.webm"], 256, scene, true);

The VideoTexture object accepts an array of videos (to take in account various codecs) and once a video can be loaded, it uses it as content source.

The internal video DOM object is accessible via property to allow you to control the status of the video (play/pause/stop).

For instance, I used this solution to simulate a TV in the Flat2009 demo:


Mirrors textures are another kind of dynamic textures. You can use them to simulate “mirrors” which mean that babylon.js will compute for you the reflection and fill the texture with the results. A Mirror texture must be set in the reflectionTexture channel of a standardMaterial:

// Mirror
var mirror = BABYLON.Mesh.createBox("Mirror", 1.0, scene);
mirror.material = new BABYLON.StandardMaterial("mirror", scene);
mirror.material.diffuseColor = new BABYLON.Color3(0.4, 0, 0);
mirror.material.reflectionTexture = new BABYLON.MirrorTexture("mirror", 512, scene, true);
mirror.material.reflectionTexture.mirrorPlane = new BABYLON.Plane(0, -1.0, 0, -2.0);
mirror.material.reflectionTexture.renderList = [box, sphere];

A mirrorTexture is created with a parameter that specify the size of the rendering buffer (512x512here). Then you have to define the reflection plane and a render list (the list of meshes to render Inside the mirror).


Importing scene from 3D assets

Babylon.js can load scenes from a file format called .babylon. This file format is based on JSON and contains all required data to create a complete scene.


A .babylon can be created with a custom tool I developed: BabylonExport. This command line tool can generate .babylon file from various file formats:

  • .FBX
  • .OBJ
  • .MXB

BabylonExport takes 2 parameters:

BabylonExport /i:”Test scenesViperViper.obj” /o:”c:ExportViper”

The tool can be found here:

Warning: The tool requires XNA 4.0 runtime:


You can also produce .babylon files with Blender. To do so, please download the exporter script right here:

A more complete article is dedicated to this feature:

To install it, please follow this small guide:

  • Unzip the file to your Blender’s plugins folder (Should be C:Program FilesBlender FoundationBlender2.67scriptsaddons for Blender 2.67 x64).
  • Launch Blender and go to File/User Préférences/Addon and select Import-Export category. You will be able to activate Babylon.js exporter.

  • Create your scene
  • Go to File/Export and select Babylon.js format. Choose a filename and you are done !

You are now able to produce .babylon scene! The exporter will be able to support more and more options in the future but right now the following features are already supported:

  • Cameras
  • Lights
  • Meshes
  • Material and Multimaterials
    • Diffuse
    • Ambient
    • Opacity
    • Reflection
    • Emissive
    • Bump
  • Collisions (with custom UI Inside Blender)
  • Fog

To learn more about how to load a blender scene:

And much more to come…

The backlog is full of cool things among which we can note:

  • Bones
  • Morphing
  • Refraction
  • Water shader

The main goal of babylon.js is to provide you with a strong framework for simplifying 3D. Use it freely as a foundation for your games and applications.

The thing that is also really cool is that you also can use Babylon.js with your Windows 8.1 apps!

So now go to and start exploring the wonderful world of 3D rendering!

Next chapters

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