HTML5 Zone is brought to you in partnership with:

I was born in 1981 in one little city. Since I was 10y/o I programmed in different languages. My first languages were basic, then C++/MFC, after .Net (C#, VB.Net, J#, ASP.Net), XSL+XML processing). In the last 5 years I worked with web languages (HTML, CSS, PHP, SQL, XML, XSL, JavaScript). After university I worked in several different companies, eventually becoming a blogger. This is my hobby too. Andrey is a DZone MVB and is not an employee of DZone and has posted 110 posts at DZone. You can read more from them at their website. View Full User Profile

WebGL with Three.JS (Lesson One)

03.12.2014
| 4725 views |
  • submit to reddit
WebGL With Three.js - Lesson 1

WebGL With Three.js – Lesson 1

As we have promised – it is time to start our new series of articles devoted to the WebGL. This is our first lesson, where we consider the main basic functions: creating a scene, camera, renderer, controls (OrbitControls). We will also create the simplest directional light, add a dozen objects (of different geometry) with shadows. In order to make things went faster, we decided to take one of the most popular webgl frameworks – three.js. Why use Three.js? Besides the fact that it is open source JavaScript framework, it is also the most rapidly growing and discussed engine. Here already implemented really many possibilities, from low-level work with points and vectors, to work with ready scenes, shaders and even stereoscopic effects.

The result of our lesson is as follows:

WebGL With Three.js - Lesson 1

Live Demo

HTML

We could omit this step, but, habitually, we do it at every lesson. So here’s the html structure of our lesson:

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <meta name="author" content="Script Tutorials" />
        <title>WebGL With Three.js - Lesson 1 | Script Tutorials</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <script src="js/three.min.js"></script>
        <script src="js/THREEx.WindowResize.js"></script>
        <script src="js/OrbitControls.js"></script>
        <script src="js/stats.min.js"></script>
        <script src="js/script.js"></script>
    </body>
</html>

In this code, we just connect all the libraries that we are going to use today.

Javascript

I hope that you have already seen our demo and imagine what the basic elements it is composed, we will consider the creation of each item step-by-step.

Skeleton

Abstractly, our scene looks like this:

var lesson1 = {
    scene: null,
    camera: null,
    renderer: null,
    container: null,
    controls: null,
    clock: null,
    stats: null,

    init: function() { // Initialization

    }
};

// Animate the scene
function animate() {
    requestAnimationFrame(animate);
    render();
    update();
}

// Update controls and stats
function update() {
    lesson1.controls.update(lesson1.clock.getDelta());
    lesson1.stats.update();
}

// Render the scene
function render() {
    if (lesson1.renderer) {
        lesson1.renderer.render(lesson1.scene, lesson1.camera);
    }
}

// Initialize lesson on page load
function initializeLesson() {
    lesson1.init();
    animate();
}

if (window.addEventListener)
    window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent)
    window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;

This is common structure of application built with three.js. Almost everything will be created in the ‘init’ function.

Creation of scene, camera and renderer

They are the main elements of our scene, they following code creates an empty scene with perspective camera and renderer with enabled shadow map:

// create main scene
this.scene = new THREE.Scene();

var SCREEN_WIDTH = window.innerWidth,
    SCREEN_HEIGHT = window.innerHeight;

// prepare camera
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000;
this.camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
this.scene.add(this.camera);
this.camera.position.set(-1000, 1000, 0);
this.camera.lookAt(new THREE.Vector3(0,0,0));

// prepare renderer
this.renderer = new THREE.WebGLRenderer({antialias:true, alpha: false});
this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
this.renderer.setClearColor(0xffffff);

this.renderer.shadowMapEnabled = true;
this.renderer.shadowMapSoft = true;

// prepare container
this.container = document.createElement('div');
document.body.appendChild(this.container);
this.container.appendChild(this.renderer.domElement);

// events
THREEx.WindowResize(this.renderer, this.camera);

We set the camera at an angle of 45 degrees, set the full screen size and white cleanup color for WebGLRenderer, added our scene in the HTML document, and also connected THREEx.WindowResize to control the renderer and the camera when resizing the window (of browser).

OrbitControls and Stats

In order to be able to somehow control the camera – three.js gives us the possibility to use ready-made controls. One of these is OrbitControls, which provides the ability to rotate the scene around its axis. Also it will be helpful to see the statistics (FPS) of our scene – a very small class Stats will help us (stats.min.js).

// prepare controls (OrbitControls)
this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
this.controls.target = new THREE.Vector3(0, 0, 0);

// prepare clock
this.clock = new THREE.Clock();

// prepare stats
this.stats = new Stats();
this.stats.domElement.style.position = 'absolute';
this.stats.domElement.style.bottom = '0px';
this.stats.domElement.style.zIndex = 10;
this.container.appendChild( this.stats.domElement );

Thus we have prepared four materials

Published at DZone with permission of Andrey Prikaznov, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)