I. Introduction to three. js framework

Three.js is a third-party WebGL library written in javascript. Using the framework of Three.js to write 3D programs, it is just like observing a 3D scene in real life, making people place themselves in it. Three. Js has three components: Scene,Camera and Render. They are the basis of the entire framework, and are used to render objects on the web and build the scene.

Scene (scene)

As the name suggests, it is used to place all the elements.

var scene = new THREE.Scene(); // Create the sceneCopy the code

Camera (camera)

The camera, where we’re going to look, how we’re going to look at these elements. There are many kinds of cameras. We will not introduce them, but here we use perspective cameras.

var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 10000); // Set the camera Angle to 60 degrees, width to height ratio, Z axis of the nearest end to 1, Z axis of the furthest end to 10000Copy the code

We can see these properties in an image from the three.js document

The renderer (render)

Once everything in the scene is ready, we can render the scene to show how we draw the elements. There are different types of renderers. Here we use the WebGLRenderer;

var renderer = new THREE.WebGLRenderer();
Copy the code

Specific steps: create elements -> define camera -> Build scene -> Put elements and camera into the scene -> Render scene specific code we will introduce later, and then let’s take a look at the renderings.

Two. Basic initialization

Here in CDN directly introducing three. Js < script SRC = “https://cdn.bootcss.com/three.js/r83/three.min.js” > < / script >

Note: some unbalanced adjustments are made because of the large difference in size, rotation speed and distance of some planets. Here’s how these elements are put in.

1.canvas

Instead of mounting the scene directly into the body, we put a Canvas canvas inside the body and display it on top of it.

Background 2.

Instead of making a 3D rotating background, we put a background image of the small solar system. The background image is placed directly on the canvas.

<canvas id="webglcanvas"</canvas> renderer = new THREE.WebGLRenderer({// define renderer alpha:true// Make the background transparent and black by default to show our own background}); renderer.setClearAlpha(0); / / CSS files#webglcanvas {
            background: url(./images/bg4.jpg) no-repeat;
            background-size: cover;
        }
Copy the code

However, this simple operation is useless, because after adding the renderer, a background color will be added with black by default. So we set its alpha property (WebGL renderer and property method) in the renderer to make the background transparent to show our own background image

3. Define the basic components

Define the scenario

Scene = new three.scene (), // create scene

Define camera position

Camera = new THREE.PerspectiveCamera(60, window.innerwidth/window.innerheight, 1,10000); Camera.position. Z = 2000; // Set the camera Angle to 60 degrees, width to height ratio, Z axis of the most end to 1, Z axis of the most end to 10000; // Adjust the camera position camera.position.y = 500;Copy the code

Create a group

A group can be thought of as a container for elements that share common characteristics.

Group = new three.group (), // create a group

I’ll explain why we created 16 additional groups in section 3.

Var group1 = new three.group (); var group1 = new three.group (); groupParent1 = new THREE.Group(); group2 = new THREE.Group(); groupParent2 = new THREE.Group(); group3 = new THREE.Group(); groupParent3 = new THREE.Group(); group4 = new THREE.Group(); groupParent4 = new THREE.Group(); group5 = new THREE.Group(); groupParent5 = new THREE.Group(); group6 = new THREE.Group(); groupParent6 = new THREE.Group(); group7 = new THREE.Group(); groupParent7 = new THREE.Group(); group8 = new THREE.Group(); groupParent8 = new THREE.Group();Copy the code

Defining the renderer

The WebGLRenderer has a canvas object to draw the output from. Now get the canvas set and put it into our canvas object in the renderer

var canvas = document.getElementById('webglcanvas'Renderer = new THREE.WebGLRenderer({// define renderer alpha:trueCanvas: canvas, // a canvas object to draw output with antialias:true// anti-aliasing}); renderer.setSize(window.innerWidth, window.innerHeight); // Set the width of the rendererCopy the code

4. Initialize the function

A series of initialization operations are performed in this function.

function init() {// Initialize the function scene.add(group); Scene.add (groupParent1); // Add groups to the scene scene.add(groupParent1); scene.add(groupParent2); scene.add(groupParent3); scene.add(groupParent4); scene.add(groupParent5); scene.add(groupParent6); scene.add(groupParent7); scene.add(groupParent8); var loader = new THREE.TextureLoader(); /* Sun loader.load()'./images/sun1.jpg'.function(texture) { var geometry = new THREE.SphereGeometry(250, 20, MeshBasicMaterial = new THREE.MeshBasicMaterial({map: Var mesh = new THREE.Mesh(geometry, material); // The first parameter of the mesh object is the geometry (structure), the second parameter is the material (appearance) group.add(mesh); // Add to group}) // Mercury loader.load('./images/water.jpg'.function(texture) {var geometry = new THREE.SphereGeometry(25, 20, 20) var material = new THREE.MeshBasicMaterial({map: Var mesh = new THREE.Mesh(geometry, material); group1.position.x -= 300; group1.add(mesh); groupParent1.add(group1); }) // The parameters of the other 7 planets are too long to be given here, but the principle of parameter setting is the same.Copy the code

A brief explanation:

var loader = new THREE.TextureLoader(); Define a material texture loader.

var geometry = new THREE.SphereGeometry(250, 20, 20); Establish a sphere model, the radius of the sphere is 250, the number of horizontal segmentation plane 20, the number of vertical segmentation plane 20.

var mesh = new THREE.Mesh(geometry, material); Mesh object.

The specific function is to create a sphere element, first build the frame, wrap it with the plane plan of the planet, form a planet, and then add the planet to the group, and then add the group to the scene. This is the process of building individual elements.

So why does the sun add directly to the group, while Mercury adds with two group levels and offsets its position? Let’s go to the third quarter.

Three. Rotation and revolution

Rotation: There are three ways to achieve rotation: 1. Rotate the camera 2. Rotate the Scene 3. Rotate individual elements.

Because each of our planets rotates at a different rate, orbits at a different rate. So it’s not feasible to set the overall rotation, so give each element a different rotation attribute.

Rotation mechanism: Here is the object’s rotation property, which rotates relative to itself.

For example: scene.rotation. Y += 0.04; // The scene rotates counterclockwise around its Y axis

Get into the business

Group. Rotation. + y = 0.04;

For the other planets to orbit the sun, they need to set themselves a position offset. For mercury: group1.position.x -= 300; Set group1.rotation. Y and it will rotate. Because its y-position has changed.

groupParent1.add(group1);

When we move group1, the position of groupParent1 does not change, so does its Y-axis. Since groupParent1 contains group1, when we rotate groupParent1, group1 will also rotate around the default initial Y-axis. So there are so many groups, in order to achieve the simultaneous rotation of each planet at different speeds and revolutions.

Other implementation functions

        function render() { renderer.render(scene, camera); camera.lookAt(scene.position); The scene is always in the middle} // Set the revolutionfunction revolution() {groupParent1. Rotation. + y = 0.15; GroupParent2. Rotation. + y = 0.065; GroupParent3. Rotation. + y = 0.05; GroupParent4. Rotation. + y = 0.03; GroupParent5. Rotation. + y = 0.001; GroupParent6. Rotation. + y = 0.02; GroupParent7. Rotation. + y = 0.0005; GroupParent8. Rotation. + y = 0.003; } // Set the rotationfunction selfRotation() {group. Rotation. + y = 0.04; Group1. Rotation. + y = 0.02; Group2. Rotation. - y = 0.005; group3.rotation.y += 1; group4.rotation.y += 1; Group5. Rotation. + y = 1.5; Group6. Rotation. + y = 1.5; Group7. Rotation. - y = 1.5; Group8. Rotation. + y = 1.2; }function Animation() {
            render();
            selfRotation();
            revolution();
            requestAnimationFrame(Animation);   
        }
Copy the code

Finally, call the init() and Animation() functions.

If you find it interesting, click 👍8.