“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

The Web has developed rapidly in recent years. With the popularity of HTML5, the performance of web pages is becoming more and more powerful. Web pages can already make a lot of complex animation, beautiful effects. Threejs allows us to easily implement 3D effects on web pages.

The sample code USES three. Js – r73 version: cdnjs.cloudflare.com/ajax/libs/t…

1. Introduce the concepts of the four components

In three. js, to render an object into a web page, we need four components: scene, camera, renderer, and Geometry. Remember the key statement: With these four things, we can use the camera to render objects from the scene onto the web page.

1. The scene

  • The scene is the stage, and you can put anything you want to show anywhere in the scene.
THREE.Scene = function ()
Copy the code
  • Create a scene
var scene = new THREE.Scene();
Copy the code
  • Q: Can we put multiple scenes in the browser?
    • The answer is yes. We can put multiple scenes in the page (new multiple scene instances)

2. The camera

  • A camera is a camera in real life, and what we end up seeing in a browser is a camera shot.
  • The camera determines which Angle of the scene the view will be displayed. The camera is just like the human eye. People can see different scenes when they stand in different positions and look up or down.
  • There is only one kind of scene, but there are many kinds of cameras. As in real life, different cameras determine all aspects of the appearance. For example, some cameras are suitable for portrait and some cameras are suitable for landscape. Professional photographers choose different cameras according to their practical purposes. For programmers, it is possible to make the camera look different by setting different camera parameters.
  • There are many kinds of cameras. Here are two kinds: perspective camera and orthographic camera

1. Perspective camera

  • Perspective camera: Perspective projection conforms to people’s psychological habits, that is, objects close to the point of view are large, objects far from the point of view are small, and objects far from the point of view disappear to the extreme, becoming the extinction point. (Near big far small)

Orthographic camera

  • The distance is the same size as the near. (Stay the same)

Note: The concept of perspective cameras and orthographic cameras is a bit like the keepSize parameter in ThingJS, which sets/gets whether an icon remains the same pixel size. The default is false, that is, the icon will appear “near larger, far smaller” in the 3D scene.

3. Camera parameters

THREE.PerspectiveCamera = function (fov, aspect, near, far)
Copy the code
  • Camera fov: The Angle between the top and bottom planes theta, which is the hardest thing to understand, my understanding is that the Angle at which your eyes open, the Angle of view, if you set it to 0, it’s like you close your eyes, so you can’t see anything. If you set it to 180, you can think of your horizon as very wide, but at 180, things tend to be very small, Because it’s smaller in proportion to your total visual area.
  • Near plane: Indicates the distance of the cutting surface near you. In addition, it can also be regarded as the distance between the eyes. Suppose it is 10 meters away, please do not set it to negative value, because it is silly, I do not know how to calculate.
  • Far plane: indicates your far plane,
  • Aspect ratio Aspect: The aspect ratio of the actual window, i.e. width divided by height. The higher the value, the wider you are, the more likely you are to be watching a wide-screen movie. If the value is less than 1, the more likely you are to be seeing an LED screen like the one shown below.

  • Code sample
var camera = new THREE.PerspectiveCamera(45, width/height, 1.1000 );
scene.add( camera );
Copy the code

3. The renderer

  • The renderer determines what elements of the page the rendered results should be drawn on, and how they should be drawn.
  • It’s like how an artist paints a scene on a screen.
  • The process of calculation is called rendering
  • Here we define a WebRenderer that looks like this:
THREE.WebGL.Renderer()
Copy the code

4. The geometry

  • Geometry, even objects to be displayed in the scene
  • The geometry is a mesh model, and if you add texture, it’s like wearing clothes. If light is added, it will show different colors of light.

2. Write the first three.js program

1. Create a scenario

In Threejs, there is only one kind of Scene, which is represented by THREE.Scene. It is easy to construct a Scene, just a new object, the code is as follows:

// 1. Define the scenario
var scene = new THREE.Scene();
console.log(scene);
Copy the code
  • A scene is a container for all objects, and if you want to display an apple, you need to add an apple object to the scene.
  • Scene has the add method, which we’ll use in a moment

2. Create a perspective camera

  • THREE.PerspectiveCameraPerspective camera
  • Create one with an Angle of 75 degrees, an aspect ratio of the camera side to the window width/window height, a near clipping side of 1, and a far clipping side of 1000
  • The units of 1 and 1000 can be either meters or centimeters. This is your own imagination.
// 2. Define camera Angle: 75 degrees, display size: window width/window height, display distance: the latest 1 meter, the furthest 1000 meters
var camera = new THREE.PerspectiveCamera(75.window.innerWidth / window.innerHeight, 1.1000 );
Copy the code

3. Create the renderer and its size

// 3. Define the renderer
var renderer = new THREE.WebGLRenderer();
renderer.setClearColor("#ffffff"); // Each time the renderer is set, empty the renderer color and turn white
// 4. Set the renderer size
renderer.setSize(window.innerWidth, window.innerHeight);
console.log(renderer);
// add the renderer to the body
document.body.appendChild(renderer.domElement);
Copy the code
  • setClearColorSets the color and its transparency
  • renderer.setSizeSets the canvas size
  • renderer.domElementIt returns a Canvas, which is automatically created by the renderer’s constructor (if no canvas argument is passed), and all renderings are drawn on domElement
  • Here,appendChildI’m going to take thisdomElementArticulated inbodyNow, the rendered results can be displayed on the page.

4. Define geometry and add it to the scene

Now that the canvas is ready, we are going to add objects to the canvas (3D geometry)

// 6. Define geometry
// Width, height, and depth are not set. Default is 1
// width, height, depth, widthSegments, heightSegments, depthSegments
var geometry = new THREE.BoxGeometry(2.2.2);
// 7. Define the material
var material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
// 8. Define mesh, geometry and materials to form mesh
var cube = new THREE.Mesh(geometry, material);
// 9. Add the grid model to the scene
scene.add(cube);
// 10. Change camera position
// The camera is at the origin and the object is at the origin, so we can't see anything
camera.position.z = 10; // Move 5 meters out of the screen
Copy the code
  • THREE.BoxGeometryBoxGeometry is the primitive geometry class of quadrilateral, which typically creates a cube or irregular quadrilateral using the “width”, “height”, and “depth” arguments provided by the constructor. This is an object that contains all the vertices and fill faces of the cube
    • Width – The width above the X axis. The default value is 1.
    • Height – The height above the Y axis. The default value is 1.
    • Depth – Depth above the Z-axis. The default value is 1.
    • WidthSegments – (optional) number of widthSegments. Default is 1.
    • HeightSegments – (Optional) Number of width segments. Default is 1.
    • DepthSegments – (Optional) Number of width segments. Default is 1.
  • THREE.MeshBasicMaterialA material that draws geometry as a simple color (flat or wireframe). This material is not affected by light.
    • Color – Can be passed as a hexadecimal string, 0xFFFFFF (white) by default, internally called color.set (color).
  • THREE.MeshRepresentation is based on trianglespolygon mesh(Polygonal mesh) object class. It also serves as a base class for other classes, such as SkinnedMesh.
    • Geometry — An instance of (optional) Geometry or BufferGeometry. The default value is a new BufferGeometry.
    • Material — (Optional) A Material, or an array containing material, defaults to a new MeshBasicMaterial.
    • That is, geometry and materials form a grid
  • When scene.add() is finally called, the object is added to the origin, the coordinate point **(0,0,0)**, which causes the camera and the cube to overlap in space. To avoid this, let’s move the camera out of position

5. Define renderer methods to render

If you copy the above code in a new creation and click run, you still won’t see anything because we haven’t actually rendered it yet. To do this, we need a render loop.

// 11. Define the render method
function render() {
  // When the browser is idle, it keeps calling the function passed in
  requestAnimationFrame(render);
  // Render the final display on renderer.domElement using the scene and camera
  renderer.render(scene, camera);
}
render();
Copy the code

This creates a loop that draws the scene 60 times per second. RequestAnimationFrame, which is used to replace setInterval, this new interface has several advantages, For example, stop rendering after Tab switching to save resources, synchronize with screen refresh to avoid invalid refresh, and safely revert to setInterval in browsers that do not support this interface.

Make things move

  • You should now see a red cube on the page, let’s add a little animation to get it moving.
  • Add the following code before renderer. Render in the render function:
function render() {
  // When the browser is idle, it keeps calling the function passed in
  requestAnimationFrame(render);
  cube.rotation.x += 0.1; // Rotate around the X-axis
  cube.rotation.y += 0.1; // Rotate around the y axis
  // Render the final display on renderer.domElement using the scene and camera
  renderer.render(scene, camera);
}
Copy the code
  • So we use three.js to create a rotating cube. Basically, if we want to change the motion of the cube, we do it in the Render loop.

  • IO/Metror /embe…

3. Summarize the relationship between scene, camera, renderer and geometry

  • The scene in three. js is a container of objects, and developers can put any geometry they need into the scene, such as apples and grapes. At the same time, the geometry itself manages its position in the scene.
  • The function of the camera is to face the scene, take a suitable scene in the scene, and take a picture of it.
  • The renderer is used to display images taken by the camera in a browser.
  • Their relationship is as follows: