start three.js

Inadvertently saw the dynamic effect of a certain official website~

It’s so handsome! very friendly

Checked the technology to achieve this effect – it turned out to be
Three.js

Then let me try Three.js dynamic 3D effects from scratch
?

?
There are a lot of cases and ways to find the source code
?

Background

With the increasing popularity of the front-end in today’s era, the effect of the page is really getting better and better!

With the development of digital image processing and artificial intelligence technology

The visual effects displayed to users are not limited to flat 2D visual effects

Began to focus on a full range of 3D stereoscopic display effects

Strive to provide 361 degrees of products without dead ends for users to understand and understand

Today~ Let’s try the excellent 3D engine Three.js for the first time

Learn

Three.js is a 3D engine based on the native WebGL package. Among all WebGL engines, Three.js is the 3D engine with the most domestic literature and the most widely used.

Threejs is a WebGL three-dimensional engine, it can be used to do many scene applications

Let me introduce the classic case of official operation

Application scenario

3D visualization of the Internet of Things

With the development of the Internet of Things, various fields such as industry and construction and the web page interaction interface of the Internet of Things related projects will present

3D trend.

The 3D method is more intuitive, and of course the development cost is relatively high

And Three.js can greatly reduce the development cost

3D Visualization Case of IoT Granary

Product 720 online preview

With the continuous promotion of WebGL technology and 5G technology, online 3D display of various products will become more and more popular

For example, a car company’s new car can be previewed online on the official website

Maybe one day some e-commerce platforms will replace 2D pictures with 3D models

Now your friend recommends a new dress to you, you will say send a picture to see

Maybe in the future you will say to send a 3D model link to have a look

sofa online preview

clothing online preview

Washing machine online interactive preview

Data visualization

Data visualization related to webgl is mainly two aspects

On the one hand, it is the visualization of massive and large data, and on the other hand, it is the visualization of data related to 3D.

For huge amounts of data

Web visualization based on canvas, svg, etc., without better performance based on WebGL technology

For 3D related data visualization based on WebGL technology

With the help of the 3D engine Threejs, it can be well realized

Analysis of GeoJOSN data China GDP data visualization

3D histogram

H5/WeChat game

The very popular WeChat mini-game Jump is developed using the Three.js engine

For the development of 3D H5 mini-games or WeChat mini-games, the Three.js engine is a very good choice. No download is required, and it is easy to spread. The current ecology is very similar to mini-game development.

Science and Education

In the field of science and education, it is more intuitive to display specific knowledge in 3D than images.

Scientific Research Platform-Protein Structure Visualization Case

Chemical Correlation – Visualization of Molecular Structures

Geography and astronomy – 3D preview of the solar system

Mechanical field

Onshape is a 3D modeling software in the mechanical field

If you are familiar with CAD software such as Solidworks and UG, then you can understand Onshape as cloud Solidworks. Mechanical model online preview demo

More

Three.js also has many exquisite application scenarios

I won’t list them all here

Friends who are happy can go to the official website of Three.js to take a look

Click here to see more

Know

Three.js resources

First look at the resources of Three.js

github link

Three.js official website

Three.js Chinese Documentation

Download the Three.js package

You can directly pull the master branch from github to the local

Because of the size of tens of M, github download threejs is relatively slow

So the author put a copy on the network disk for everyone to download

Network disk resources

First taste

First follow the official website to familiarize yourself with the local case of Three.js

Local initialization project

Initialize directory structure

Create ThreeJs folder Create index.html file

create js folder

Put the downloaded three.js package into the js folder

Case 1: The first 3D scene

<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <title>The first three.js file_WebGL 3D scene</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      /* Hide the scroll bar in the body window area */
    }
  </style>
  <!--Introduce three.js three-dimensional engine-->
  <!-- <script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>-->
  <script src="js/three/build/three.js"></script>
  <!-- <script src="http://www.yanhuangxueyuan.com/threejs/build/three.js"></script> -->
</head>
 
<body>
  <script>
    /**
     * Create scene object Scene
     */
    var scene = new THREE. Scene();
    /**
     * Create mesh model
     */
    // var geometry = new THREE.SphereGeometry(60, 40, 40); // Create a sphere geometry object
    var geometry = new THREE.BoxGeometry(100, 100, 100); //Create a cube geometry object Geometry
    var material = new THREE. MeshLambertMaterial({
      color: 0x0000ff
    }); //Material object Material
    var mesh = new THREE.Mesh(geometry, material); //Mesh model object Mesh
    scene.add(mesh); //Add the grid model to the scene
    /**
     * Light source settings
     */
    //point Light
    var point = new THREE. PointLight(0xffffff);
    point.position.set(400, 200, 300); //Point light position
    scene.add(point); //point light source added to the scene
    //ambient light
    var ambient = new THREE. AmbientLight(0x444444);
    scene. add(ambient);
    // console. log(scene)
    // console. log(scene. children)
    /**
     * Camera settings
     */
    var width = window.innerWidth; //window width
    var height = window.innerHeight; //window height
    var k = width / height; // window aspect ratio
    var s = 200; //3D scene display range control coefficient, the larger the coefficient, the larger the display range
    // create camera object
    var camera = new THREE. OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    camera.position.set(200, 300, 200); //Set camera position
    camera.lookAt(scene.position); //Set the camera direction (the scene object pointed to)
    /**
     * Create a renderer object
     */
    var renderer = new THREE. WebGLRenderer();
    renderer.setSize(width, height);//Set the rendering area size
    renderer.setClearColor(0xb9d3ff, 1); //Set the background color
    document.body.appendChild(renderer.domElement); //insert the canvas object into the body element
    //Execute the rendering operation, specify the scene and camera as parameters
    renderer. render(scene, camera);
  </script>
</body>
</html>

The structure of the whole program:

Case 2: Rotation animation, cycle rendering

In Case 1, a 3D cube model has been made

On this basis, we try to rotate it

cycle rendering

Every time you execute the rendering method .render() of the renderer object WebGLRenderer, the browser will render a frame of image and display it on the web page, which means that you can call the rendering method .render() continuously according to a certain cycle Continuously generate new images to overwrite the original images. This means that as long as the cube is rotated and the rendering method .render() is executed to re-render, the rotation effect of the cube can be achieved.

So we can use the timer + render() in js to move the 3D cube

Change the code to:

renderer.render(scene, camera);

Replace with:si

// rendering function
function render() {
    renderer.render(scene,camera);//perform rendering operation
    mesh.rotateY(0.01);//rotate 0.01 radians around the y-axis each time
}
//Call the function fun periodically at intervals of 20ms, 20ms means the refresh rate is 50FPS (1s/20ms), rendering 50 times per second
setInterval(render,20);
Copy Code

The official here says that the rendering frequency of calling the rendering method .render() for rendering should not be too low

//Set the cycle of calling the render function to 200ms, and the refresh rate is equivalent to 5, you can clearly feel the lag
setInterval("render()",200);

function requestAnimationFrame()

In actual development, in order to make better use of browser rendering, you can use the function requestAnimationFrame() instead of the setInterval() function

The parameter of requestAnimationFrame() is the function name of the function to be called. RequestAnimationFrame() calls a function instead of calling it immediately but sends a request to the browser to execute a certain function. When it will be executed is determined by the browser. Generally, the default frequency is 60FPS. , The function specified by the requestAnimationFrame() method is called about every 16.7ms. 60FPS is ideal. If the rendered scene is more complex or the hardware performance is limited, it may be lower than this frequency. can view the article
“requestAnimationFrame()” Learn more about the requestAnimationFrame() function.

function render() {
        renderer.render(scene,camera);//perform rendering operation
        mesh.rotateY(0.01);//rotate 0.01 radians around the y-axis each time
        requestAnimationFrame(render);//Request to execute the rendering function render again
    }
render();

Case 3: Mouse operation 3D scene

Code Implementation

function render() {
  renderer.render(scene,camera);//perform rendering operation
}
render();
var controls = new THREE.OrbitControls(camera,renderer.domElement);//create control object
controls.addEventListener('change', render);//monitor mouse and keyboard events
Copy Code

The OrbitControls.js control provides a constructor THREE.OrbitControls(). When a camera object is used as a parameter, the code new THREE.OrbitControls(camera,renderer.domElement) is executed, and the browser will automatically detect the changes of the mouse and keyboard, and according to Mouse and keyboard changes update the parameters of the camera object.

For example, if you drag the left mouse button, the browser will detect the mouse event and convert the mouse translation distance into the rotation angle of the camera according to a certain algorithm. You can contact the camera in your life to take pictures. Even if the scene does not change, your camera shooting angle If there is a change, the result rendered by the natural renderer will change. By defining the listening event controls.addEventListener(‘change’, render), if you operate the mouse continuously, the parameters of the camera will change continuously, and at the same time it will Call the rendering function render() to render, so that threejs will use the new camera position or angle data for rendering.

Executing the constructor THREE.OrbitControls(), the browser will do two things at the same time. One is to define a mouse and keyboard event for the browser, and automatically detect changes in the mouse and keyboard. If there is a change, it will automatically update the data of the camera. Execute this The constructor will return an object at the same time, you can add an event listener to the object, as long as the mouse or keyboard changes, the rendering function will be triggered.

Scene operation

  • Zoom: scroll – middle mouse button

  • Rotate: drag – left mouse button

  • Pan: drag – right mouse button

requestAnimationFrame() usage

If the periodic call of the renderer rendering method render() is implemented through requestAnimationFrame() in the threejs code

When changing the camera state through the OrbitControls operation

There is no need to call the rendering function by listening to the mouse event through controls.addEventListener(‘change’, render)

Because requestAnimationFrame() will keep calling the rendering function.

function render() {
  renderer.render(scene,camera);//perform rendering operation
  // mesh.rotateY(0.01);//rotate 0.01 radians around the y-axis each time
  requestAnimationFrame(render);//Request to execute the rendering function render again
}
render();
var controls = new THREE.OrbitControls(camera);//create control object
// The render function has been executed periodically through requestAnimationFrame(render); there is no need to execute the render function by listening to mouse events
// controls. addEventListener('change', render)
Copy Code

Note the official conflict matters

Be careful not to use requestAnimationFrame() or controls.addEventListener(‘change’, render) to call the same function at the same time during development, as this will conflict.

This is the first time to try the Three.js case. I believe that interested friends have a little understanding of this. The next study is up to you to explore by yourself!

Three.js Tutorial

Official case

Is it the first time to try Three.js and only “taste” these few cases are not fun!

It doesn’t matter! Let’s take a look at the excellent cases of the official website

And find their source code!

Display

Some of the very good Amway I came to Amway, right?

  • gpgpu_birds

  • geometry_minecraft

  • effects_anaglyph

  • animation_skinning_morph

  • buffergeometry_drawrange

The above Amway is just the Amway that I think is interesting~ There are nearly hundreds of cases on the official website
What are you waiting for! Hurry up to experience the wonderful effect of Three.js~

Source code

I found many excellent cases on the official website~

How can I get its source code?

I sorted out two methods to query its source code

  1. There is a button in the lower right corner of the official website

Click the button to enter the case source code in github

  1. All official website cases can be found under the tree folder

tree > examples > [case name].html

So we got our first taste of Tree.js

have to say! This is really “delicious”