Three.js is a JavaScript library for creating 3D Web graphics in a Web browser.
What is WebGL?
WebGL is a JavaScript API that allows browsers to render 3D graphics without using any plug-ins. WebGL allows GPU-accelerated rendering within HTML5 canvas elements on web pages. The first stable version 1.0 was released in March 2011, and now version 2.0 is available in January 2017.
The target
- Start using the three.js library
- Create the first scenario
- Put something in the scene
- Let’s get it moving
- Give the scene some light
The installation
This is a beginner’s guide, so start with the easiest way. Only two files index. HTML and main.js will be used. Starting with an HTML file, make a basic HTML page and import the three.js library.
<! DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, Scalable =no, minimum-scale=1.0, maximum-scale=1.0" /> <title>Three. Js DEMO</title> <style> body {margin: 0; } canvas { width: 100%; height: 100%; } </style> </head> <body> <! -- CDN Link to Three.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.js"></script> <script src="./main.js"></script> </body> </html>Copy the code
Now looking at the JavaScript file, whenever three.js is used, the basics that need to be set up are the scene, camera, and renderer.
const scene = new THREE.Scene(); Const camera = new THREE.PerspectiveCamera(75, window.innerwidth/window.innerheight, 0.1, 1000); const renderer = new THREE.WebGLRenderer({ antialias: true });Copy the code
Start with a scene, you’ll add it later, but now you’ll create a new scene element with no parameters. The camera will use the PerspectiveCamera option. There are four default cameras available, but PerspectiveCamera is a good starting point to mimic the human eye. We need to give this function four arguments:
- Field of view: The width of the camera’s view Angle.
- Aspect ratio: like a TV screen, e.g. width/height.
- Near clipping plane: Elements closer than this do not appear on the screen. If the movie is being shot, then anything behind the camera will not appear, and for this, basically use
0
. - Far clipping plane: Elements farther than this are not rendered, and high values can cause performance problems.
The renderer will take the option object and will only use {Antialiasing: True} to have a smoother edge on the cube to be created. It doesn’t have to be, but it looks better. Next you need to set the size of the curtain.
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
Copy the code
Set the renderer to the size of the entire window and tell it to append itself to the body of the HTML page with the following effect:
The next step is to create the cube, which requires a scene, camera, and renderer to get started. Again, three core elements are needed to process each object you want to render:
- Geometry: The shape of an object, consisting of vertices (points) and surfaces (planes of the object). Three.js also gives a lot of prefabricated geometry just give it some parameters and it will handle the details there.
- Material: What objects are made of, and this will include things like color, which will determine how light interacts with our objects. If there is a pebble and a metal ball bearing, they will have similar geometry, but their materials are very different, which will change how it looks to the audience.
- Mesh: Combination of geometry and materials.
Now look at the complete code, as follows:
const scene = new THREE.Scene(); Const camera = new THREE.PerspectiveCamera(75, window.innerwidth/window.innerheight, 0.1, 1000); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.setClearColor("#222222"); document.body.appendChild(renderer.domElement); camera.position.z = 5; // resize event window.adDeventListener ("resize", () => {let width = window.innerWidth; let height = window.innerHeight; renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); }); // Open geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshStandardMaterial({ color: 0xff0051, flatShading: true, metalness: 0, roughness: 1, }); const cube = new THREE.Mesh(geometry, material); scene.add(cube); Const geometry2 = new THREE.BoxGeometry(3, 3, 3); const material2 = new THREE.MeshBasicMaterial({ color: "#dadada", wireframe: true, transparent: true, }); const wireframeCube = new THREE.Mesh(geometry2, material2); scene.add(wireframeCube); // Const ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.2); scene.add(ambientLight); // const pointLight = new three. pointLight (0xFFFFFF, 1); pointLight.position.set(25, 50, 25); scene.add(pointLight); function animate() { requestAnimationFrame(animate); Cube. Rotation. X + = 0.04; Cube. Rotation. + y = 0.04; WireframeCube. Rotation. X = 0.01; WireframeCube. Rotation. - y = 0.01; renderer.render(scene, camera); } animate();Copy the code
The BoxGeometry method will take the constructor parameters, which are the width, height, and depth of the box.
For the material, we will use the most basic supply material that is not affected by the light source and give it a color option, color: 0xFF0051. The real power of 3D rendering comes from how it handles light sources to create realistic scenes. How reflective materials are, how shadows, how colors appear, and so on, all depend on light, starting with the most basic form of light in Three.js and the new AmbientLight.
Const ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.2); scene.add(ambientLight);Copy the code
Create a light source and tell it the color and how intense it should be. Ambient light is everywhere and applies to everything. It can’t cast shadows because it has no direction. It just changes the way our colors appear.
Next, you create a point light source, which you can think of as a light bulb, from which light travels evenly in all directions from the origin.
const pointLight = new THREE.PointLight(0xffffff, 1);
pointLight.position.set(25, 50, 25);
scene.add(pointLight);
Copy the code
The last piece of the puzzle is to change the cube material, choosing the most basic material that does not interact with light, but can now use a light source, changing the previous material code to:
const material = new THREE.MeshStandardMaterial({
color: 0xff0051,
flatShading: true,
metalness: 0,
roughness: 1,
});
Copy the code
Now look at the full effect, as follows: