Three.js is a powerful and popular JavaScript library for creating 3D graphics and animations on the web. Whether you’re a seasoned 3D developer or just getting started, three.js provides a wealth of features and functions to help you create stunning visual experiences. In this article, we will dive into the details of three.js, covering everything from its basic concepts to its advanced features. We’ll explain each function in detail, provide code examples, and show you how to use three.js to create amazing 3D graphics and animations. With this comprehensive guide, you’ll be able to master three.js and start creating your own 3D graphics and animations in no time!
Here are some of the commonly used functions in three.js with examples:
Scene
A scene is a container that holds all the objects and lights in your 3D world. You can create a new scene using the following code:
const scene = new THREE.Scene();
The following are the parameters commonly used when creating a scene in Three.js:
- background: The background color of the scene, specified as a color value or an image URL.
- fog: The fog effect applied to the scene, specified as a fog object with properties such as color and density.
- autoUpdate: A boolean value that determines whether the scene will automatically update its objects.
- matrixAutoUpdate: A boolean value that determines whether the scene’s matrix will automatically update.
- lights: An array of lights added to the scene, used to illuminate objects and cast shadows.
- objects: An array of objects added to the scene, including meshes, cameras, and lights.
- overrideMaterial: A material that will be applied to all objects in the scene, overriding their individual materials.
- userData: An object that can be used to store custom data associated with the scene.
These parameters are used to define the appearance and behavior of the scene, such as its background color, lighting, and objects. They can be adjusted and updated at runtime to control the look and feel of the scene and the objects within it.
Here’s an example of creating a scene in Three.js with parameters:
const scene = new THREE.Scene(); // Set the background color of the scene scene.background = new THREE.Color( 0xffffff ); // Add fog effect to the scene scene.fog = new THREE.Fog( 0xcccccc, 200, 1000 ); // Automatically update scene scene.autoUpdate = true; // Add a light to the scene const light = new THREE.DirectionalLight( 0xffffff, 1 ); light.position.set( 1, 1, 1 ); scene.add( light ); // Add a cube to the scene const cubeGeometry = new THREE.BoxGeometry( 1, 1, 1 ); const cubeMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ); const cube = new THREE.Mesh( cubeGeometry, cubeMaterial ); scene.add( cube ); // Override material for all objects in the scene scene.overrideMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } ); // Add custom data to the scene scene.userData.customData = { message: "Hello World!" };
In this example, we first create a new THREE.Scene
and set its background color to white (0xffffff). We then add a fog effect with a color of light gray (0xcccccc) and a density ranging from 200 to 1000. The scene is set to automatically update its objects.
We then add a directional light to the scene and a green cube with a lambert material. We override the material for all objects in the scene with a wireframe red material, and finally, add some custom data to the scene in the form of a customData
property.
Camera
A camera defines the point of view from which you view the 3D scene. You can create a new camera using the following code:
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
The following are the parameters commonly used when creating a PerspectiveCamera in Three.js:
- fov (Field of View): The field of view of the camera, which determines the extent of the scene that is seen on the screen.
- aspect: The aspect ratio of the camera, which determines the relationship between the width and height of the camera’s viewport.
- near: The near clipping plane, which determines the closest point in the scene that the camera can see.
- far: The far clipping plane, which determines the farthest point in the scene that the camera can see.
- position: The position of the camera in the 3D world, specified as a vector.
- target: The target point that the camera is looking at, specified as a vector.
- up: The upward direction of the camera, specified as a vector.
These parameters define the perspective and viewing angle of the camera and control the area of the scene that is visible to the camera. The PerspectiveCamera is used to create a more realistic, three-dimensional view of the scene, as it simulates the way that human eyes see the world.
Render
A render is used to render the 3D scene in a web browser. You can create a new renderer using the following code:
const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement );
The following are the parameters commonly used when creating a WebGLRenderer in Three.js:
- canvas: The canvas element that the renderer will use to display the scene.
- context: The WebGL context to use for rendering.
- alpha: A boolean value that determines whether the renderer should have an alpha channel.
- antialias: A boolean value that determines whether antialiasing should be applied to the render.
- autoClear: A boolean value that determines whether the renderer should automatically clear the color, depth, and stencil buffers before rendering.
- sortObjects: A boolean value that determines whether the renderer should sort the objects in the scene by depth.
- devicePixelRatio: The device pixel ratio to use when rendering, used to adjust the resolution of the renderer to the device.
Here’s an example of creating a WebGLRenderer in Three.js with parameters:
const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById("myCanvas"), alpha: true, antialias: true }); // Set the size of the renderer renderer.setSize( window.innerWidth, window.innerHeight ); // Enable automatic clearing of buffers before rendering renderer.autoClear = true; // Enable sorting of objects by depth renderer.sortObjects = true; // Set the device pixel ratio renderer.devicePixelRatio = window.devicePixelRatio;
In this example, we first create a new THREE.WebGLRenderer
and pass in an options object with the canvas element and the desired alpha and antialias values. We then set the size of the renderer to the window’s inner width and height. The autoClear
property is set to true
to enable automatic clearing of the color, depth, and stencil buffers before rendering, and the sortObjects
property is set to true
to sort the objects in the scene by depth. Finally, we set the device pixel ratio to the window’s device pixel ratio to adjust the resolution of the renderer to the device.
Geometry
A geometry defines the shape of an object in the 3D scene. You can create a new geometry using the following code:
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
The following are the parameters commonly used when creating a BoxGeometry
in Three.js:
- width: The width of the box.
- height: The height of the box.
- depth: The depth of the box.
- widthSegments: The number of segments to use along the width of the box.
- heightSegments: The number of segments to use along the height of the box.
- depthSegments: The number of segments to use along the depth of the box.
Here’s an example of creating a BoxGeometry
in Three.js with parameters:
const geometry = new THREE.BoxGeometry( 1, 2, 3, 4, 5, 6 );
In this example, we create a new THREE.BoxGeometry
with a width of 1
, a height of 2
, and a depth of 3
. The widthSegments
, heightSegments
, and depthSegments
properties are set to 4
, 5
, and 6
respectively. This will create a box with the specified dimensions and the specified number of segments along each axis.
Material
A material defines the appearance of an object in the 3D scene. You can create a new material using the following code:
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
The following are the parameters commonly used when creating a MeshBasicMaterial
in Three.js:
- color: The color of the material.
- map: A texture map to apply to the material.
- wireframe: A boolean value that determines whether the material should be rendered as a wireframe.
- wireframeLinewidth: The width of the lines used to render the wireframe.
- transparent: A boolean value that determines whether the material should be transparent.
- opacity: The opacity of the material.
Here’s an example of creating a MeshBasicMaterial
in Three.js with parameters:
const material = new THREE.MeshBasicMaterial({ color: 0xffffff, map: texture, wireframe: true, wireframeLinewidth: 1, transparent: true, opacity: 0.5 });
In this example, we create a new THREE.MeshBasicMaterial
and pass in an options object with the desired properties. The color
property is set to 0xffffff
(white), the map
property is set to the texture texture
, the wireframe
property is set to true
to render the material as a wireframe, the wireframeLinewidth
property is set to 1
to set the width of the wireframe lines, the transparent
property is set to true
to make the material transparent, and the opacity
property is set to 0.5
to set the opacity of the material.
Mesh
A mesh is a combination of geometry and material. It is the final object that you see in the 3D scene. You can create a new mesh using the following code:
const cube = new THREE.Mesh( geometry, material ); scene.add( cube );
The following are the parameters commonly used when creating a Mesh
in Three.js:
- geometry: The geometry to use for the mesh.
- material: The material to use for the mesh.
- position: The position of the mesh in the scene.
- rotation: The rotation of the mesh in the scene.
- scale: The scale of the mesh in the scene.
- castShadow: A boolean value that determines whether the mesh should cast shadows.
- receiveShadow: A boolean value that determines whether the mesh should receive shadows.
Here’s an example of creating a Mesh
in Three.js with parameters:
const mesh = new THREE.Mesh( geometry, material ); mesh.position.set( 1, 2, 3 ); mesh.rotation.set( 0, Math.PI / 2, 0 ); mesh.scale.set( 2, 2, 2 ); mesh.castShadow = true; mesh.receiveShadow = true;
In this example, we create a new THREE.Mesh
and pass in the geometry
and material
parameters. We then set the position
of the mesh to (1, 2, 3)
, the rotation
to (0, Math.PI / 2, 0)
, and the scale
to `(2, 2, 2). We also set
castShadowto
trueso that the mesh will cast shadows, and
receiveShadowto
true` so that the mesh will receive shadows.
animate
animate is a function used to continuously render the 3D scene. You can create an animate function using the following code:
function animate() { requestAnimationFrame( animate ); cube.rotation.x += 0.01; cube.rotation.y += 0.01; renderer.render( scene, camera ); } animate();
The animate
function is used to create an animation loop in Three.js. This function is called repeatedly using requestAnimationFrame
to update and render the scene.
Here’s a detailed explanation of the function:
requestAnimationFrame
: TherequestAnimationFrame
method is used to request that the browser call theanimate
function before the next repaint. This allows the animation to run smoothly, syncing the updates with the display refresh rate.cube.rotation.x += 0.01
: Thex
rotation of thecube
is incremented by0.01
in each iteration of the loop. This causes thecube
to rotate around its x-axis.cube.rotation.y += 0.01
: They
rotation of thecube
is incremented by0.01
in each iteration of the loop. This causes thecube
to rotate around its y-axis.renderer.render( scene, camera )
: Therender
method of therenderer
is called to render thescene
using thecamera
. Thescene
andcamera
parameters define what is being rendered and from what perspective.animate()
: Finally, theanimate
function is called to start the animation loop.
This function creates an animation that continuously updates the rotation of the cube
and renders the scene using the renderer
. The result is a smooth animation of a rotating cube.
Light
Lights are used to illuminate the 3D scene. You can create a new light using the following code:
const light = new THREE.PointLight( 0xff0000, 1, 100 ); light.position.set( 50, 50, 50 ); scene.add( light );
The following are the parameters commonly used when creating a PointLight
in Three.js:
- color: The color of the light.
- intensity: The intensity of the light.
- distance: The distance at which the light’s intensity is 0.
- decay: The rate at which the light’s intensity decreases as the distance from the light source increases.
In this example, we create a new THREE.PointLight
and pass in the color
, intensity
, distance
, and decay
parameters. The color
is set to 0xffffff
(white), the intensity
is set to 1
, the distance
is set to 100
, and the decay
is set to 2
. We then set the position
of the light to (0, 10, 0)
.
This creates a point light with a white color, intensity of 1
, distance of 100
, and decay of 2
, positioned at (0, 10, 0)
.
AmbientLight
AmbientLight is a type of light that illuminates all objects in the scene equally, regardless of their position. You can create a new AmbientLight using the following code:
const ambientLight = new THREE.AmbientLight( 0x404040 ); // soft white light scene.add( ambientLight );
The following are the parameters commonly used when creating an AmbientLight
in Three.js:
- color: The color of the light.
In this example, we create a new THREE.AmbientLight
and pass in the color
parameter. The color
is set to 0x404040
(dark gray).
This creates an ambient light with a dark gray color, which provides a basic level of illumination for the entire scene.
SpotLight
SpotLight is a type of light that illuminates a specific area in the scene. You can create a new SpotLight using the following code:
const spotLight = new THREE.SpotLight( 0xffffff ); spotLight.position.set( 100, 1000, 100 ); scene.add( spotLight );
The following are the parameters commonly used when creating a SpotLight
in Three.js:
- color: The color of the light.
- intensity: The intensity of the light.
- distance: The distance at which the light’s intensity is 0.
- angle: The angle, in radians, of the light’s cone of influence.
- penumbra: The size of the penumbra (the outer region of the light’s cone where the light’s intensity decreases).
- decay: The rate at which the light’s intensity decreases as the distance from the light source increases.
Here’s an example of creating a SpotLight
in Three.js with parameters:
const light = new THREE.SpotLight( 0xffffff, 1, 100, Math.PI / 6, 0.2, 2 ); light.position.set( 0, 10, 0 ); light.target.position.set( 0, 0, 0 );
In this example, we create a new THREE.SpotLight
and pass in the color
, intensity
, distance
, angle
, penumbra
, and decay
parameters. The color
is set to 0xffffff
(white), the intensity
is set to 1
, the distance
is set to 100
, the angle
is set to Math.PI / 6
(30 degrees), the penumbra
is set to 0.2
, and the decay
is set to 2
. We then set the position
of the light to (0, 10, 0)
and set the position
of the light’s target
to (0, 0, 0)
.
This creates a spot light with a white color, intensity of 1
, distance of 100
, angle of 30 degrees
, penumbra of 0.2
, and decay of 2
, positioned at (0, 10, 0)
and aimed at the origin (0, 0, 0)
.
Raycaster
Raycaster is used to detect intersections between a ray and objects in the 3D scene. You can create a new Raycaster using the following code:
const raycaster = new THREE.Raycaster(); const mouse = new THREE.Vector2();
The following are the parameters commonly used when creating a Raycaster
in Three.js:
- origin: The origin of the ray.
- direction: The direction of the ray.
- near: The minimum distance from the origin at which objects will be intersected by the ray.
- far: The maximum distance from the origin at which objects will be intersected by the ray.
Here’s an example of creating a Raycaster
in Three.js with parameters:
const raycaster = new THREE.Raycaster( new THREE.Vector3(), new THREE.Vector3( 0, -1, 0 ), 0, 10 );
In this example, we create a new THREE.Raycaster
and pass in the origin
, direction
, near
, and far
parameters. The origin
is set to a new THREE.Vector3()
, which will be the starting point of the ray. The direction
is set to new THREE.Vector3(0, -1, 0)
, which represents the direction of the ray. The near
parameter is set to 0
, meaning the ray will start at its origin, and the far
parameter is set to 10
, meaning the ray will extend to a distance of 10
units.
This creates a raycaster with origin (0, 0, 0)
, direction (0, -1, 0)
, minimum distance 0
, and maximum distance 10
. The raycaster can be used to detect objects in the scene that intersect with the ray.
OrbitControls
OrbitControls is a helper class that allows you to control the camera and view the 3D scene from different angles. You can create new OrbitControls using the following code:
const controls = new THREE.OrbitControls( camera, renderer.domElement );
The following are the parameters commonly used when creating OrbitControls
in Three.js:
- object: The object to be controlled, typically a camera.
- domElement: The DOM element in which the controls should be rendered.
In this example, we create a new THREE.OrbitControls
and pass in the camera
and renderer.domElement
parameters. The camera
parameter is the camera object that we want to control, and the renderer.domElement
parameter is the DOM element in which the controls will be rendered.
This creates an OrbitControls object that can be used to rotate the camera around a target in a scene.
TextGeometry
TextGeometry is used to create 3D text in the scene. You can create a new TextGeometry using the following code:
const textGeometry = new THREE.TextGeometry( 'Hello, Three.js!', { font: font, size: 80, height: 5, curveSegments: 12, bevelEnabled: true, bevelThickness: 10, bevelSize: 8, bevelOffset: 0, bevelSegments: 5 });
The following are the parameters commonly used when creating a TextGeometry
in Three.js:
- text: The text that should be rendered as a geometry.
- parameters: An object containing various parameters for text rendering such as font, size, height, curveSegments, etc.
In this example, we create a new THREE.TextGeometry
and pass in the text
and parameters
parameters. The text
parameter is set to "Hello, World!"
, which is the text that will be rendered. The parameters
parameter is an object that contains various properties for text rendering.
The properties in the parameters
object include the font (font
), size (size
), height (height
), curveSegments (curveSegments
), bevelEnabled (bevelEnabled
), bevelThickness (bevelThickness
), bevelSize (bevelSize
), and bevelSegments (bevelSegments
).
This creates a TextGeometry
object that can be used to render text in a Three.js scene.
Loaders
Three.js provides a number of loaders to load 3D models and other assets into the scene. Some of the commonly used loaders are:
- OBJLoader: Loads OBJ files, which are a widely used file format for 3D models.
- GLTFLoader: Loads GLTF files, which is a 3D file format with smaller file size and faster loading times.
- ColladaLoader: Loads Collada files, which is a widely used open standard for exchanging 3D assets.
- FBXLoader: Loads FBX files, which is a proprietary file format used in the entertainment industry.
Here’s an example of how you can use the OBJLoader to load a 3D model into the scene:
const objLoader = new THREE.OBJLoader(); objLoader.load( 'model.obj', function ( object ) { scene.add( object ); });
The following are the parameters commonly used when creating an OBJLoader
in Three.js:
- manager: A loading manager that helps track and manage multiple loaders.
Here’s an example of creating an OBJLoader
in Three.js with parameters:
const objLoader = new THREE.OBJLoader(manager);
In this example, we create a new THREE.OBJLoader
and pass in the manager
parameter. The manager
parameter is an optional loading manager that can help track and manage multiple loaders.
This creates an OBJLoader
object that can be used to load .obj files in a Three.js scene. To actually load an .obj file, you would use the load
method, like this:
objLoader.load("path/to/file.obj", function (object) { scene.add(object); });
In this example, the objLoader.load
method is used to load an .obj file located at path/to/file.obj
. The second parameter is a callback function that is executed once the file has finished loading. The loaded object is added to the scene using the scene.add
method.
Materials
Three.js provides a number of materials to give your 3D objects different appearances. Some of the commonly used materials are:
- MeshBasicMaterial: A basic material with a solid color.
- MeshLambertMaterial: A material that reacts to light, making it look more realistic.
- MeshPhongMaterial: A material that adds specular highlights, making it look more polished.
- MeshStandardMaterial: A physically based material that reacts to light in a more realistic way.
- MeshPhysicalMaterial: A more advanced version of MeshStandardMaterial, with more parameters to control the material’s appearance.
Here’s an example of how you can use MeshLambertMaterial to give a 3D object a more realistic appearance:
const material = new THREE.MeshLambertMaterial( { color: 0xff0000 } ); const cube = new THREE.Mesh( geometry, material ); scene.add( cube );
The following are the parameters commonly used when creating a MeshLambertMaterial
in Three.js:
- color: The color of the material. This can be specified as a hexadecimal value, a CSS-style string, or a Three.js
Color
object. - emissive: The emissive (glow) color of the material.
- reflectivity: The reflectivity of the material, which determines how much it reflects light.
- opacity: The opacity of the material, with 1 being completely opaque and 0 being completely transparent.
- wireframe: A boolean that determines whether the material should be rendered as a wireframe.
Here’s an example of creating a MeshLambertMaterial
in Three.js with parameters:
const material = new THREE.MeshLambertMaterial({ color: 0x00ff00, emissive: 0x003300, reflectivity: 1, opacity: 1, wireframe: false });
In this example, we create a new THREE.MeshLambertMaterial
and pass in an options object. The options object sets the color
of the material to green (0x00ff00), the emissive
color to dark green (0x003300), the reflectivity
to 1, the opacity
to 1 (fully opaque), and sets wireframe
to false (not rendered as a wireframe).
This creates a MeshLambertMaterial
object that can be used as the material for a Three.js mesh. For example:
const geometry = new THREE.BoxGeometry(1, 1, 1); const cube = new THREE.Mesh(geometry, material); scene.add(cube);
In this example, we create a BoxGeometry
object with dimensions 1x1x1, and a Mesh
object that uses the material
we created earlier. The Mesh
object is then added to the scene using the scene.add
method.
Animations
Three.js provides a number of methods to animate objects in the scene. Some of the commonly used animation techniques are:
- Keyframe Animation: This technique involves specifying a set of keyframes that define the animation, and the library interpolates the values between the keyframes to create the animation.
- Tween Animation: This technique involves specifying the starting and ending values of the animation, and the library uses easing functions to create the animation.
- Procedural Animation: This technique involves writing custom code to animate the objects in the scene.
Here’s an example of how you can use Tween Animation to animate an object’s position:
const tween = new TWEEN.Tween( object.position ) .to( { x: 100 }, 1000 ) .easing( TWEEN.Easing.Linear.None ) .onUpdate( function () { renderer.render( scene, camera ); }) .start();
The following are the parameters commonly used when creating a Tween
in Three.js:
- object: The object that will be animated.
- to: An object with the final properties for the object being animated.
- duration: The length of time in milliseconds that the animation should last.
- easing: The easing function to use for the animation.
- onUpdate: A callback function that will be called on each animation update.
- onComplete: A callback function that will be called when the animation is completed.
Here’s an example of creating a Tween
in Three.js:
const to = { x: 5, y: 0, z: 5 }; const duration = 1000; const easing = TWEEN.Easing.Quadratic.InOut; const onUpdate = function() { console.log('Tween animation updated'); }; const onComplete = function() { console.log('Tween animation complete'); }; const tween = new TWEEN.Tween(object.position) .to(to, duration) .easing(easing) .onUpdate(onUpdate) .onComplete(onComplete); tween.start();
In this example, we create a Tween
object that animates the position
property of an object
. We specify the final to
values as { x: 5, y: 0, z: 5 }
, set the duration
of the animation to 1000 milliseconds, specify an easing function of TWEEN.Easing.Quadratic.InOut
, and set the onUpdate
and onComplete
callback functions.
Finally, we start the animation using the tween.start
method. The animation will run for 1000 milliseconds, updating the position of the object
over time, and calling the onUpdate
and onComplete
functions as appropriate.
In conclusion, three.js is an essential tool for creating 3D graphics and animations on the web. With its rich features and functions, it offers endless possibilities for creating stunning visual experiences. From simple shapes to complex animations, three.js has you covered. Whether you’re a beginner or an experienced developer, this guide provides a comprehensive overview of three.js, making it easy to get started and master the library. We hope this article has given you a good understanding of three.js and how it can help you bring your 3D graphics and animations to life. So start exploring, and let your imagination run wild with three.js!
No Comments
Leave a comment Cancel