3D experience in a browser with Three.js
Join the DZone community and get the full member experience.Join For Free
Three.js is a library for rendering 3D models into a browser, without using Flash or other third-party plugins. In 3D graphics, the actual model of a scene is built in a solid space (three dimensions, obviously), and depending of the current view point, lighting and other parameters a new view is generated. Usually thirty times a second...
The technology side
- The canvas element is part of the HTML 5 standard, but it was introduced before by Webkit and then Gecko browsers several years ago.
Domain side (3D models)
Three.js models concepts like a scene and the object present in it, a renderer, and a camera. It requires at least a primer in 3D graphigs: for example, the Lambertian and Phong reflection models to specify for surfaces are domain specific terms.
Most of the concepts I've seen in the examples are accessible to computer engineers: 3D cartesian coordinates, a camera with an aspect ratio, and solid geometry.
Full of examples
The performance will depend on your browser too: I have tried it with Firefox and Chrome, and the former is noticeably less responsive.
In the examples, usually the orientation of the camera follows the mouse, or it is draggable with a click and zoomable with the scroll. The examples guarantee 30 to 60 frames rendered per second, but of course the amount of detail required may lower the performance.
By the way, since I know all developers are hungry for code, here is how the code looks like (non functional sample, just initialization):
// set the scene size var WIDTH = 400, HEIGHT = 300; // set some camera attributes var VIEW_ANGLE = 45, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 10000; // get the DOM element to attach to // - assume we've got jQuery to hand var $container = $('#container'); // create a WebGL renderer, camera // and a scene var renderer = new THREE.WebGLRenderer(); var camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR ); var scene = new THREE.Scene(); // the camera starts at 0,0,0 so pull it back camera.position.z = 300; // start the renderer renderer.setSize(WIDTH, HEIGHT); // attach the render-supplied DOM element $container.append(renderer.domElement);
You can check the examples out by loading the examples/ folder of your working copy.
We are at the start of the journey of 3D in the browser, and it's promising. After all, Tomb Raider games were a huge success, even on consoles like the first Playstation where they provided an inferior performance with respect to PCs.
Opinions expressed by DZone contributors are their own.