The author | edit | jing Lou, guo poetry

Shiya Guo holds a master’s degree in Computer Science and Technology from South China University of Technology. She is currently working as a UI development engineer at Tencent ISUX (Social User Experience Design Department).

background

Js is a third-party 3D library written in javascript based on webGL, through which 3D modeling can be carried out in web pages. Combined with tweenmax.js animation library, it becomes very easy to achieve 3D animation effects in web pages.

Here is a simple process legend modeled by Three.js:

In plain words, first of all, you can use js to create various shapes of geometry, or import from outside building model file, and then add material to geometry (texture, color, etc.), it formed a mesh grid model, we can create a lot of model, the container into the scene, the scene also add lights, The camera is “lit” to capture objects in the scene. To capture a moving scene, the camera shoots and the renderer keeps rendering it to the screen (rendering loop) until the screen displays a 3D moving scene.

Since it is through the camera to shoot the scene, so that we can see on the screen, then move the camera to shoot the world from different angles, naturally can see a different world.

Three. The camera in js

The cameras in three.js are divided into two types, one is orthographic projection camera and the other is perspective projection camera. The general differences between the two types are as follows:

(Image from webGL Chinese)

In perspective projection, an object of the same size will be smaller under the screen at a distance than an object close to it, while in orthography they will be the same size.

In this example, we use perspective projection. The instantiation code is as follows:

camera = new THREE.PerspectiveCamera(45, width / height, 1.10000);
Copy the code

The four parameters represent the Angle of view, the ratio of the width to height of the window to be seen, the closest distance to be seen, and the farthest distance to be seen. The larger the Angle, the larger the area of the scene and the smaller the objects you can see.

Then comes the setting of camera position. When initializing a camera, three properties, position/ Up /lookAt, are generally set first. Use a demo to illustrate these three attributes. Before that, let’s first understand the coordinate system of three.js, which is right-handed coordinate system, as shown in the figure below:

Thumb in the x direction, index finger in the Y direction, middle finger in the Z direction.

Back to the camera initialization code:

camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 500;
camera.up.x = 0;
camera.up.y = 1;
camera.up.z = 0;
camera.lookAt({x : 0 ,y : 0, z : 0});
Copy the code
  1. Camera. position: as the name implies, it is the position of the camera in the coordinate system, which is 500 points from the origin to the z axis.

  2. Camera. Up: it is difficult to understand, which means that the direction of the “top of the camera” is in the same direction as the vector (0,1,0), that is, in the same direction as the positive direction of the Y-axis. To understand this, draw a picture:

  1. Camera. LookAt: Refers to where the camera is facing, in this case directly to the origin.

In addition, the camera. Up direction must not be parallel to the camera position and the lookAt line, otherwise the scene will not be shot

Demo implementation process – calculation

1. Preparation process

After initializing three.js, create the object we need. Here I randomly create several cubes with random sizes and positions. Load a picture texture on the side facing the screen as the front, as shown below:

If you look from the positive direction of y axis to the negative direction of Y axis, the schematic diagram looks like this (the blue represents the cube, the side with thick line and arrow represents the front of the cube with picture, the black cylinder represents the camera, and the arrow indicates the shooting direction) :

The next step is the animation process. It should be noted that in the following steps, the object rotates only in the Y direction and only moves in the X/Z direction, thus transforming the motion of a three-dimensional space into a two-dimensional space

2. Move the camera to the Y-axis, rotate the cube and the camera so that they are aligned, as shown in the picture below:

During initialization, we recorded the coordinate value of the cube (x,y,z), and the rotation Angle of the cube from the screen to the Y-axis. I used the junior middle school mathematics method — inverse trigonometric function to calculate it. The figure below shows the angles that the objects in the four quadrants need to rotate.

After the cube is rotated, the camera only needs to rotate the same Angle as the cube and move the y value in the coordinate to the same direction as the cube to photograph the front of the cube.

  1. As the cubes mentioned before are of different sizes, it is necessary to move the camera so that the distance between the camera and the cube is in proportion to the size of the cube, so that we can see the same size of each cube. Therefore, the displacement of the camera needs to be calculated, as shown below:

We know the side length of the cube A, assume that the distance between the camera and the center point of the cube is set as 3a, and use the principle of equal proportion of the side length of similar triangles to get the coordinates of the place where the camera should be moved (X2,z2), the formula is as follows:

  1. In order to make the cube have the feeling of random placement, we can also rotate the cube around a certain Angle randomly in the Y direction, and then rotate the camera around the center point of the cube to the position directly facing the front of the cube:

The calculation method is as follows:

As shown in the figure above, the camera was originally the coordinate (x,z) on the line between the center of the cube and the origin. After rotating the random Angle θ around the center point of the cube (rx,rz), the calculation formula of (x’,z’) is as follows:

Math.atan()\math.cos() and so on.

Demo implementation process – animation

Above the step 2, 3, in the process of direct call TweenMax. Js animation library, to control the camera. The position/camera rotation. However, in the fourth step, transform-Origin cannot be directly set as the center point of the cube like CSS, so it must be realized by itself. For example, control displacement:


TweenMax.to(
    camera.position,  // Specify control attributes
    2.// Animation time
    {x:x2,y: mesh[index].position.y,z:z2,delay:0,ease:Cubic.easeIn} // The distance to move
);
Copy the code

RequestAnimationFrame () is used to implement this by changing the rotation and position of the camera little by little until the Angle θ is reached.

var rate;  // Rotation frequency
function cameraRoAni(){
    var ani;
    // The rotation Angle of the object is greater than 0
    if (rotateMesh[index- 1] > 0) {
        rotateRate = rotateRate + rate;
        if(rotateRate <= rotateMesh[index- 1]) {var newX = (camera.position.x - mesh[index- 1].position.x)*Math.cos(-rate) - (camera.position.z - mesh[index- 1].position.z)*Math.sin(-rate) +  mesh[index- 1].position.x;
            var newZ = (camera.position.x - mesh[index- 1].position.x)*Math.sin(-rate) + (camera.position.z - mesh[index- 1].position.z)*Math.cos(-rate) +  mesh[index- 1].position.z;
            camera.position.x = newX;
            camera.position.z = newZ;
            camera.rotation.y += rate;
            ani = requestAnimationFrame(cameraRoAni);
        }else{
            cancelAnimationFrame(ani);
        }
    // The rotation Angle of the object is less than 0
    }else{...// The code is similar to that greater than 0
        }else{ cancelAnimationFrame(ani); }}if (rate>0.01) {
        rate = rate - 0.0001; }}Copy the code

conclusion

You can do a lot of 3D motion by just changing the camera in three.js

Put a demo address: kiroroyoyo. Making. IO/threejsexam… (Sometimes the randomness of Angle and cube is too strong to control it, welcome to put forward correction and optimization!!)


Related to recommend

GraphWalker is a model-based automated testing tool