net - UK (2020-03)

(Antfer) #1

PROJECTS
three.js


For simplicity, we’ll add the video tag direct to the
HTML page. This makes it easier for you to see the
video during testing as well. Notice we set the muted,
playsinline and autoplay properties to ensure the
video can play both on desktop and mobile. Replace
the video with any video you wish. MP4 format
is best for this but ultimately any web-supported
formats will work.

<video id=”video” src=’assets/MyVideo.mp4’
crossOrigin=”anonymous” style=”display:none” playsinline
class=’background-video’ src=’’ loop preload muted=”true”
></video>

STEP 4: SET UP GLOBAL VARIABLES
Next, you should set up a few simple variables to
keep track of scene, camera, renderer, the orbit controls
and the container that contains the HTML canvas. Add
this code first between the script tags:

var container, controls, camera, scene, renderer;

STEP 5: CALL INIT AND ANIMATE
FUNCTIONS
Call the init and animate functions, now that the page
is loaded and accessible. You’ll write those functions
in the next steps.

init();
animate();

STEP 6: CREATE THE ANIMATION/
RENDER LOOP
Define the animate function you called in the last
step. It’s straightforward to animate in three.js.
Using the requestAnimationFrame to manage the
frequency of the renders, we ensure the animation
stops when the browser window is not active and
that the render is only run when the browser can
handle it. This will run at 60 frames per second in
most situations. We then ask the renderer to render
the scene to the canvas. Use the following code to
do that:

function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}

STEP 7: INIT FUNCTION
Create the init function to hold the rest of the
initialisation code:

function init() {
}

STEP 8: 3D CAMERA
To see your scene, add a 3D perspective camera. The
code will first go inside your init function. The first
parameter for the camera object is the field of view.
The second is the aspect ratio, followed by the near
and far clipping planes.

camera = new THREE.PerspectiveCamera( 45, window.
innerWidth / window.innerHeight, 1, 2500 );
camera.position.set( 0,0,1000);

STEP 9: 3D SCENE
Now create a scene to hold your camera and 3D
objects. You can set a fog for the scene, so it
gradually fades the pixels to the colour you define.
You can also specify a default background colour or
an environment map if you wish.

scene = new THREE.Scene();
scene.fog = THREE.Fog(0,100,0x000000);

STEP 10: CREATE A RENDERER
Next add the renderer, which handles drawing the
scene to the HTML canvas element. You can also

Top To test the scene is all
working so far, add a simple
Plane object
Above Creating a
VideoTexture enables video
to be copied to the material
each render frame
Free download pdf