(click anywhere to close)
OPEN MENU

[Three.js] A Beginners Guide

category: Games | course: Threejs | difficulty:

Three.js is an amazing javascript library that makes creating WebGL (= 3D in the browser) games much, much easier. It's available as a single, minified javascript file to include in your html page. From there on, you can use all of its useful features to create your 3D game (or application). However, you obviously can'tjust include the file and expect magic things to happen, you have to learn how to use and work with the engine! Well, you've come to the right place, as this is the tutorial that will get you up and running.

- Get the Three.js library here(click it, save the page as 'three.min.js', and you're good to go!)

3D? That sounds amazing...but difficult

Well yes, and no. The world of 3D is one dimension larger than the 2D one, and that requires quite a bit of extra stuff to take care of and keep in mind when creating your game (cameras, lightning, materials, etc.). Creating something in 3D, especially if you're completely new to games, requires from you to acquire the proper mindset:you can't just drop a square into the world, and all will be alright. The square needs (x,y,z) positions, dimensions, material, shaders, shadows, a camera pointed at it, lightning to actually show it, etc.

But, if you want to achieve any type of realistic or POV look, trying to fake it using 2D methods is much harder than just taking the extra time and using native 3D

Creating a basic 3D scene

This might all sound scary, but luckily, setting up a basic scene with Three.js is actually very, very easy. To display any 3D-program on a computer, you need a few things:

  • A renderer: something that renders the complete 3D scene
  • A scene: a space where everything is created and takes place
  • A camera: a camera through which we view the world

Creating the .html file

Any HTML5 game can be accessed by simply going to its website/page. Therefore, the first thing you do with any browser game, is create its HTMLwebpage.

<!DOCTYPE html>
<html>
	<head>
		<title>Some Cool 3D Game</title>
		<style>canvas { width: 100%; height: 100% }</style>
	</head>
	<body>
        <!-- Include the javascript library -->
		<script src="js/three.min.js"></script>
        <!-- Here goes all our game's code -->
		<script>
			
		</script>
	</body>
</html>

Creating the basics for any HTML5 game

Any HTML5 game has a loop at its core, its heart that keeps beating, that works like this:we tell JavaScript to call a certain function about 60 times per second (depends on the framerate you choose or what your system can handle). Every time the function is called, the complete screen is cleared of all objects, and then the whole game is drawn again with the updated positions/rotations/objects/etc. Luckily, the good people creating JavaScript, have created a function for just that.

function render()
{  
	//Loop this render function we're in at 60 frames/second
	//Also, when we're not focussed on this webpage, this pauses our game (useful!)
    requestAnimationFrame(render);

	//All the logic for your game comes here, this is where all the magic happens
    ...

    //And once the magic has happened, we tell THREE.JS to update the scene according to the new standards
    //'renderer' is a variable we'll define in the next part
    renderer.render(scene, camera);
}

//And last but not least, don't forget to call the function ONCE
render();

Creating the basics of a Three.js 3D scene

Now that the game's webpage is created, and we're sure we're looping our game at a comfortable framerate, we need to initiate Three.js and create a basic scene we can do stuff with later on. As stated earlier, we're going to need a few different things for it to work. Put this just after the <script> tag, before your render() function:

//Set the size of the game
//If you want it fullscreen, use window.innerWidth and window.innerHeight
var WIDTH = 400,
  HEIGHT = 300;

//Set the attributes for our camera (field of view, aspect ratio, near point, far point)
//Near and far point specify in which area things will be rendered in front of the camera
//Set them to values closer to each other if you want a more efficient game, otherwise just leave it this way
var VIEW_ANGLE = 45,
  ASPECT = WIDTH / HEIGHT,
  NEAR = 0.1,
  FAR = 10000;

//Create the renderer (WebGLRenderer is standard, there are others, but those are just automatic fallbacks for older browsers)
var renderer = new THREE.WebGLRenderer();

//Create the camera using our predefined variables
var camera =
  new THREE.PerspectiveCamera(
    VIEW_ANGLE,
    ASPECT,
    NEAR,
    FAR);

//Create the scene
var scene = new THREE.Scene();

//Add the camera to it, and pull it back a bit, because it starts at (0,0,0)
scene.add(camera);
camera.position.z = 20;

//Set the size of the renderer
renderer.setSize(WIDTH, HEIGHT);

//Assuming you've created an element with id 'gameCanvas' you want to put your game in..
//Get this element, and append the renderer to it, to start things off
var c = document.getElementById("gameCanvas");
c.appendChild(renderer.domElement);

Okay...nice I guess?

Now you should see no errors, and there should be a 3D scene loaded into your canvas. However, nothing is actually in the scene, so there's really nothing to see. Now would be the time to start putting objects or so-called geometries into the scene. I'll demonstrate the regular simple box/cube.

It's a cube!

The code explains itself (this still needs to be put before the render() function, because we're simply creating something, and not updating anything).

//Create geometry for the object (a cube with dimensions (1,1,1))
var geometry = new THREE.BoxGeometry(1,1,1);
//Create a material for it
//The MeshBasicMaterial is one of the materials included, and is a material that doesn't care about lightning or anything,
//but is useful for testing out things
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

//Create the cube, by telling Three.js to create a new mesh, providing it with our cube's geometry and material
//NOTE: This means, that you can create a more complex geometry, and then only call THREE.Mesh once to draw 'em all, which reduces CPU load!
var cube = new THREE.Mesh( geometry, material );

//Finally add the cube to the scene
scene.add(cube);

The reader who's been paying attention might now ask the question 'but, there's no light, why do we see the cube?'. When we don't give THREE.js a light, it just lights the whole scene with an universal, global light. This might be useful in some cases, but looks horrific in most cases.

I like to move it move it

The last pieceofthis beginners tutorial will be showing you how to make the cube actually do something. Put this in the render() function, right between the requestAnimationFrame, and the renderer call:

cube.rotation.x += 0.1;
cube.rotation.y += 0.1;

What now?

It would be wise, to continue with our advanced tutorial. This covers the extra basic possibilities of Three.js, some extra features you will find useful, and links to more specific tutorials on Three.js subjects.

CONTINUE WITH THIS COURSE
No previous post :( [Three.js] An Advanced Guide
Do you like my tutorials?
To keep this site running, donate some motivational food!
Crisps
(€2.00)
Chocolate Milk
(€3.50)
Pizza
(€5.00)