Three.js Basics

BinaryCodex
2 min readApr 11, 2017

--

Three.js is a lightweight JavaScript 3D library to render canvas on web browser. It uses WebGL renderer to render on browser. WebGL (Web Graphics Library) is a JavaScript API for rendering 3D graphics on web browser.

Make sure your browser supports WebGL and you can check WebGL for your browser here

Installing Three.js

  1. Content Delivery Network (CDN)
https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js

2. Bower

bower install three --save

3. NPM

npm install three --save

4. Download manually here

https://github.com/mrdoob/three.js/archive/master.zip

Let’s start with the code

Start with the basic HTML Boilerplate

<html>    <head>        <meta charset="utf-8">        <title>Three.js Basics</title>    </head>    <body>    </body></html>

Importing Three.js

<script src="node_modules/three/build/three.min.js"></script>

Creating Scene, Render and Camera

  • Scene is an area where we can place things like geometry, lights, camera and more.
  • Renderer is what makes an object appear on the screen.
  • Camera tells the renderer from which point of view it must render on the screen.
<body>    <script type="text/javascript">        // create scene        var scene = new THREE.Scene();        // create renderer        var renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });        renderer.setSize(500, 500);        renderer.setClearColor(0xffffff, 1); // sets to white colour        // append renderer to html        document.body.appendChild(renderer.domElement);        // create camera        var camera = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);        camera.position.set(0, 0, 10); // sets z position of camera        scene.add(camera);    </script><body>

Creating a Sphere using Geometry, Material and Mesh

  • Geometry concerns with shapes, size, positions and properties of objects.
  • Material describes the appearance of objects.
  • Mesh is an object that applies a material to a geometry.
// create geometryvar geometry = new THREE.SphereGeometry(5, 100, 100);// create materialvar material = new THREE.MeshBasicMaterial({ color: 0xC6ED2C, wireframe: true }); // set colour and wireframe to true// create mesh - mixing geometry and materialvar sphere = new THREE.Mesh(geometry, material);scene.add(sphere); // adding sphere to scene

Render everything to screen

  • requestAnimationFrame function request renderer to animate the scene and camera on the screen.
var animate = function () {    requestAnimationFrame(animate);    renderer.render(scene, camera);}// calling animate function to render on screenanimate();

Further Reading

Stay tuned for next post :)

--

--

BinaryCodex

A Developer Duo trying to ease new & old concepts for newbies in the community. Harsh Thakkar, Front End Web Developer & Midhet Sulemani, Mobile Developer