What are you in the mood for today?

Sunday, 13 October 2013

Welcome to the new world of 3D in your browser! Today I'm going to show you just how easy it can be with a help from BabylonJs. BabylonJs is a high level wrapper on top of WebGL. With libraries like this, it is actually very easy to make things like the above scene.

The first thing we will need is some css for where we want the rendered image to be drawn.

To help keep our code clean you will now create a "myCode.js". I hope you noticed that this file is the one referenced in the above section.

In side "myCode.js" we will add the following:

function babylon(){
//get a reference to the canvas element on the page
var canvas = document.getElementById("canvasView");
//create an instance of the rendering engine
var engine = new BABYLON.Engine(canvas, true);
//create an instance of a Scene.
//This is used to house our camera, lights and shapes
var scene = new BABYLON.Scene(engine);

Now that we have a Scene, we need to specify a camera

//a Camera, so the renderer knows what to show us.
var camera = new BABYLON.FreeCamera("Camera", new BABYLON.Vector3(0, 0, -10), scene);

Now we will get the ball rolling by creating a render function to be looped over.

// Render loop
var renderLoop = function () {
// Start new frame
engine.beginFrame();
// process scene
//NOTE: at this point the "beforeRender" will be called
scene.render();
// draw
engine.endFrame();
// Need this to render the next frame
BABYLON.Tools.QueueNewFrame(renderLoop);
};
//Need this to call the renderLoop for the 1st time
BABYLON.Tools.QueueNewFrame(renderLoop);

One final this we should do is to check if the browser supports WebGL

}// END OF babylon funciton
//Check it there browser is supported
if (BABYLON.Engine.isSupported()) {
babylon();
}
else{
alert("Sorry! WebGL is to cool for your Browser")
}