Moment For Technology

Try three.js from scratch [Lots of cases, simple start]

Posted on Dec. 2, 2022, 12:19 a.m. by Dale Bishop
Category: The front end Tag: The front end three.js

Inadvertently saw a dynamic effect of the official website ~ is really too handsome! Very friendly to check the technology to achieve this effect - it turns out to be three.js so let me taste the dynamic 3D effect of three.js from zero ✨ ✨ there are a lot of cases and ways to find the source oh ✨


background

As front ends become more and more popular these days, page implementations are getting really good! With the development of digital image processing and artificial intelligence technology, the visual effect shown to users is not limited to the 2D visual effect of the plane, and began to pay attention to the full range of 3D three-dimensional display effect, and strive to have no dead Angle to the product 361 degrees for users to understand and understand today ~ follow greatly to taste the excellent THREE-DIMENSIONAL engine three.js


To understand

Three.js is a 3D engine based on the encapsulation and operation of native WebGL. Among all WebGL engines, three. js is the 3d engine with the most texts and the most widely used in China.

Threejs is a WebGL 3D engine that can be used for many, many scenarios

Let me introduce the classic case of official operation below

Application scenarios

3D visualization of the Internet of Things

With the development of the Internet of Things, the Web interface of Web projects related to the Internet of things in various fields such as industry and architecture will show the trend of 3D. The 3D way is more intuitive, of course, the development cost is also relatively large, and three. js can greatly reduce the development cost of iot granaries 3D visualization case

Product 720 preview online

As WebGL technology continues to be promoted, 5G technology continues to be promoted, 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 its official website. Maybe one day some e-commerce platforms will replace 2D pictures with 3D models. You're going to say send a picture and see maybe in the future you're going to say send a link to a 3D model and see an online preview of a sofa and an online preview of a garment and an online interactive preview of a washing machine

Data visualization

Webgl-related data visualization mainly includes two aspects: one is the visualization of massive and super large data; the other is the visualization of 3D related data. Web visualization based on Canvas, SVG and other methods for large and massive data For 3D related data visualization based on WebGL technology, 3D engine Threejs can be well implemented to parse GeoJOSN data and visualize 3D histogram of China's GDP data

H5/ wechat small game

Very popular micro channel game jump jump is the use of three. js engine development of the development of 3D H5 mini game or micro channel game, three. js engine is a very good choice oh no download, convenient dissemination, the current ecology is very and small game development.

Field of science and education

In the field of science and education, displaying specific knowledge in 3D is more intuitive than visuals. Research platform - Protein structure visualization case chemistry related - Molecular structure visualization geography and astronomy related - Solar system 3D preview

Mechanical field

Onshape is a mechanical field of THREE-DIMENSIONAL modeling software if familiar with Solidworks, UG and other CAD software, then you can understand Onshape as cloud Solidworks. Mechanical model online preview demo

More and more

There are many exquisite application scenarios of three.js. Oh, here is not a list of happy friends can go to the official website of three.js to have a look at oh, poke poke here to see more oh


know

Three. Js resources

First take a look at the resources of three.js

Github Three. Js website Three. Js Chinese document

Download Three. Js package

You can pull the master branch directly from Github

Because there are dozens of M size, Github download Threejs is slow so the author put a web disk, convenient for everyone to download oh web disk resources


At the beginning of taste

First, follow the official website to get familiar with the local case of three.js

Initialize the project locally

Initialize the directory structure

Create the ThreeJs folder create the index.html file create the JS folder put the downloaded three.js package in the JS folder

Example 1: The first 3D scene

! DOCTYPEhtml
html lang="en"

head
  meta charset="UTF-8"
  titleThe first three.js file _WebGL 3D scene/title
  style
    body {
      margin: 0;
      overflow: hidden;
      /* Hide the body window area scroll bar */
    }
  /style
  ! -- Introduction of three.js 3d 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 a grid model */
    // var geometry = new THREE.SphereGeometry(60, 40, 40); // Create a sphere geometry object
    var geometry = new THREE.BoxGeometry(100.100.100); // Create the cube Geometry object Geometry
    var material = new THREE.MeshLambertMaterial({
      color: 0x0000ff
    }); // The object is called "Material"
    var mesh = new THREE.Mesh(geometry, material); // The Mesh model object
    scene.add(mesh); // Add the grid model to the scene
    /** * Light source Settings */
    / / the point light source
    var point = new THREE.PointLight(0xffffff);
    point.position.set(400.200.300); // Point light source location
    scene.add(point); // Add point light to scene
    / / the 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 the camera object
    var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1.1000);
    camera.position.set(200.300.200); // Set the camera position
    camera.lookAt(scene.position); // Set camera orientation (scene object to point to)
    /** * Create a renderer object */
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);// Set the render area size
    renderer.setClearColor(0xb9d3ff.1); // Set the background color
    document.body.appendChild(renderer.domElement); // Insert a Canvas object into the body element
    // Execute the render operation specifying the scene and camera as parameters
    renderer.render(scene, camera);
  /script
/body
/html
Copy the code


The structure of the entire program:

Case 2: rotation animation, cycle rendering

In case one, we've made a model of a 3D cube and based on that, we try to rotate it

Cycle rendering

Every time the render method of the WebGLRenderer object is executed, the browser render() will render a frame and display it on the Web page, which means that you will call the render method repeatedly in a certain period of time. This means that you can rotate the cube by performing the render() method while rotating it.

So we can use javascript timer +render() to animate the 3D cube

The code:

renderer.render(scene,camera);
Copy the code

Replace with: si

Function render() {render(scene,camera); // Execute the render operation mesh.rotateY(0.01); SetInterval (render,20); // setInterval(render,20); // setInterval(render,20);Copy the code

The render() method must not render too often

SetInterval ("render()",200); setInterval("render()",200);Copy the code

Function requestAnimationFrame ()

In practice, you can use requestAnimationFrame() instead of setInterval() to make better use of browser rendering

The requestAnimationFrame() argument is the name of the function to be called. RequestAnimationFrame () does not call a function immediately. Instead, it makes a request to the browser to execute the function. The default is to maintain a frequency of 60FPS, which is about every 16.7ms to call the function specified by the requestAnimationFrame() method. 60FPS is ideal, but may be lower if the rendered scene is more complex or the hardware performance is limited. See the requestAnimationFrame() article to learn more about the requestAnimationFrame() function.

function render() { renderer.render(scene,camera); // Execute the render operation mesh.rotateY(0.01); RequestAnimationFrame (render); } render();Copy the code

Case 3: Mouse operation 3d scene

Code implementation

function render() { renderer.render(scene,camera); } render(); var controls = new THREE.OrbitControls(camera,renderer.domElement); / / create the control object controls. AddEventListener (' change ', render); // Listen for mouse and keyboard eventsCopy the code

The Orbitcontrols.js control provides a constructor, three.orbitcontrols (). When taking a camera object as an argument, Execute code new THREE. OrbitControls (camera, the renderer. DomElement accordingly), the browser will automatically detect the change of the mouse and keyboard, according to the changes of the mouse and keyboard to update the parameters of the camera object.

For example, if you drag the left button of the mouse, the browser will detect the mouse event and convert the distance of the mouse translation into the rotation Angle of the camera according to a certain algorithm. You can take photos with the camera in your life. Even if the scenery does not change, the shooting Angle of your camera changes, and the results rendered by the natural renderer will change. By defining controls, monitoring events. AddEventListener (' change ', render), if you continuous operation of the mouse, the camera's parameters change, at the same time will keep call the render function render () rendering, Threejs then uses the camera's new position or Angle data for rendering.

Execute the constructor three.Orbitcontrols () and the browser does two things at the same time. First, it defines a mouse and keyboard event for the browser. If the mouse and keyboard change, it automatically updates the camera data. You can add a listener event to this object that will trigger the render function whenever the mouse or keyboard changes.

Scene operation

  • Zoom: Scroll - middle mouse button
  • Rotate: Drag - left mouse button
  • Pan: Drag - right mouse button

RequestAnimationFrame () usage

If threejs code implements the renderer via requestAnimationFrame(), the render() method is periodically called when changing the camera state via OrbitControls No need through controls. AddEventListener (' change ', render) rendering function called listen for mouse events Because requestAnimationFrame () will call the render function.

function render() { renderer.render(scene,camera); // Mesh. RotateY (0.01); RequestAnimationFrame (render); } render(); var controls = new THREE.OrbitControls(camera); // requestAnimationFrame(render) has been passed; Periodically perform render function. There is no need to through the monitor function to be executed render mouse events / / controls. The addEventListener (' change ', render)Copy the code

Effect:

Pay attention to official conflicts

Don't used at the same time pay attention to the development of requestAnimationFrame () or controls. The addEventListener (' change ', render) call the same function, it will conflict.

This first taste of three.js case is here oh ~ I believe that interested partners also have a little understanding of this, the next study, rely on you partners to explore!

Three. Js


The official case

Is not the first time to try three.js only "taste" these several cases are not addictive ah! It doesn't matter! Let's take a look at the official website excellent cases and find their source code!

Three. Js website excellent case

show

Let me try some of the best ones in Amway

  • gpgpu_birds

  • geometry_minecraft

  • effects_anaglyph

  • animation_skinning_morph

  • buffergeometry_drawrange

The above amway is just my own interesting amway oh, there are nearly 100 cases in the website waiting for what! Go ahead and experience the wonderful effects of Three.js

The source code

To the official website found a lot of excellent cases ~ that how to get to its source code

I sorted out two ways to query its source oh

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

Click the button to enter the github case source code


  1. All official site cases can be found in the Tree folder

Tree Examples [case name].html

This is our first taste of tree.js have to say! This is really delicious.


Stern said

It was a pleasure to share this article with you. If this article helped you in any way, give it a like ?

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.