Build a 3D Sphere with WebGL – BabylonJS Series part 1

BabylonJS Series by David Catuhe (@DeltaKosh):

Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

Tutorial

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

Babylon JS 01

Final result

How can I do this ?

You can develop this scene very easily in 2 simple step.

Before you start, be sure to have a WebGL compatible browser (e.g. “IE 11” on Windows 8.1).

The web part

First of all, create a basic HTML5 web page (Visual Studio is your friend):

 
 
    
 
 
 


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

  • In the body part:
  • And in the head part, we put our CSS to view the canvas in maximum size:
       html, body, div, canvas {
                width: 100%;
                height: 100%;
                padding: 0;
                margin: 0;
                overflow: hidden;
        }
    

     

The JavaScript part

Now we have an empty web page, ready to display 3D! Let magic happen by adding the Babylon JavaScript source code in the head section:

(if you don’t already got those files, you can find them here: https://github.com/BabylonJS/Babylon.js, and here: http://handjs.codeplex.com/)

Then finally, at the end of our web page(after body, load the engine and create your scene! A scene is composed by:

  • The Babylon engine
  • A scene object
  • A camera
  • At least one light
  • A render loop, to display your scene continuously

Loading the engine…


  // Get the Canvas element from our HTML below
  var canvas = document.getElementById("renderCanvas");
  // Load BABYLON 3D engine
  var engine = new BABYLON.Engine(canvas, true);

And let your imagination run wild as you create incredible scenes like this one:

  var scene = new BABYLON.Scene(engine);

  // Creating a camera looking to the zero point (0,0,0), a light, and a sphere of size 1
  var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
  var light0 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 0, 10), scene);
  var origin = BABYLON.Mesh.CreateSphere("origin", 10, 1.0, scene);

  // Attach the camera to the scene
  scene.activeCamera.attachControl(canvas);

  // Once the scene is loaded, just register a render loop to render it
  engine.runRenderLoop(function () {
    scene.render();
  });


And you are already done! Now, you should see your sphere in 3D within your browser.

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