First, learning and harvest
1. The relationship between OpenGL, WebGL, Canvas and three.js
2. Three. Js Three elements
3. Basic elements of three.js
4. Use of Three. Js plug-ins
5. Use three. js to display 3D geometry
Ii. Main Contents:
1. Three. Js Prerequisites
Talking about Three. Js, we need to talk about OpenGL and WebGL first. OpenGL is a cross-platform 3D/2D drawing standard (specification), WebGL (Web Graphics Library) is a 3D drawing protocol. It allows JavaScript and OpenGL to be used together, but using WebGL’s native API to write 3D programs is very complicated and requires a relatively large amount of math knowledge, which is very expensive for front-end developers to learn.
1.1 WebGL
WebGL is a 3D graphical interface for Javascript that combines Javascript with OpenGL ES 2.0.
OpenGL 1.2
OpenGL is an open graphics standard, cross-programming languages, cross-platform, Javascript, Java, C, C++, Python and other can support OpenGL, OpenGL Javascript implementation is WebGL. OpenGL ES 2.0 is a subset of OpenGL, designed for mobile phones, game consoles and other embedded devices.
1.3 Canvas
Canvas is the Canvas element of HTML5. When using Canvas, it needs to use the Canvas context. 2D context can be used to draw 2D images, and 3D context can also be used to draw 3D images, where 3D context refers to WebGL.
2. What is three.js?
Official website: Javascript 3D Library. Three. Js is an easy-to-use and lightweight 3D library based on webGL encapsulation. It has a very good encapsulation of the interface provided by webGL, simplifies many details, greatly reduces the learning cost, greatly improves the performance, and has very powerful functions. It can easily create 3D graphics, is the main tool for front-end developers to develop 3D graphics. Wechat small game Tiaoyitiao is also based on three.js development, Threejs is now leading the way.
In short: Three.js is a JS library that can achieve 3D effects
3. OpenGL, WebGL, Canvas, three.js
OpenGL: 3D drawing standard
WebGL: OpenGL + JavaScript
Canvas: WebGL + Canvas 2D
Three.js: a library based on WebGL encapsulation
Similar to:
ECMAscript: Scripting language specification
JavaScript: Scripting language
JQuery: a library based on JavaScript encapsulation
In a nutshell: WebGL and three. js are the same as JavaScript and jQuery.
4. What are the application scenarios of Three.js?
(1) Web 3D games
(2) 3D object model display
(3) Data visualization
(4) Web VR
(5) Display of other special effects
5. Preparation of three.js
1. WebGL supported browsers:
- Google Chrome 9+
- Firefox 4+
- Opera 15+
- Safari 5.1 +
- Internet Explorer 11
- Microsoft Edge
** Chrome is recommended **
2. Three-dimensional coordinate system in three.js
In three.js, space is presented based on a right-handed Cartesian coordinate system:
Three-dimensional coordinate system in three.js:
3. Two ways to introduce the three. js library
1, by way of CDN introducing < script SRC = “https://cdn.bootcss.com/three.js/92/three.js” > < / script >
6. Three. Js basic case presentation
<html>
<head>
<title>Basic case of three.js</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script src="https://cdn.bootcss.com/three.js/r83/three.min.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(
50.window.innerWidth / window.innerHeight,
0.1.1000
);
camera.position.set(5.10.10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(4.4.4);
var materialBasic = new THREE.MeshBasicMaterial({
color: 0xffffff.wireframe: true
});
var materialNormal = new THREE.MeshNormalMaterial();
var cube = THREE.SceneUtils.createMultiMaterialObject(geometry, [
materialBasic,
materialNormal
]);
camera.lookAt(cube.position);
scene.add(cube);
var spotLight = new THREE.SpotLight(0xffffff);
spotLight.position.set(0.20.20);
spotLight.intensity = 5;
scene.add(spotLight);
var axes = new THREE.AxisHelper(6);
scene.add(axes);
renderer.render(scene, camera);
</script>
</body>
</html>
Copy the code
To use three-dimensional space, you need to create a container of three-dimensional space, which we usually call a scene.
7. Three elements of Thress.js (core) :
Scene, camera, renderer
The camera captures what is displayed in the scene and then renders it onto the canvas using a renderer
(1) The scene
A scene is a three-dimensional space, a container for storing all objects. It can be thought of as an empty room in which objects to be presented, cameras, light sources, etc.
Where and what the scene allows to be rendered to three.js, the scene is where objects, lights and cameras are placed.
Var scene = new three.scene () var scene = new three.scene ()
var scene = new THREE.Scene(); // Create a scene
Copy the code
2. Camera
We need to add a camera to the scene, the camera is used to determine the observation position, direction, Angle, what the camera sees, is what we finally see on the screen. In the process of running the program, you can adjust the position, direction and Angle of the camera.
Imagine putting a camera in a room, and you’re not in the room, but you can move the camera remotely, and the camera feeds the remote computer the image that Threejs shows on the screen.
Two types of cameras are commonly used in three.js: perspectiveCamera and OrthographicCamera.
PerspectiveCamera [important]
** Features: ** Perspective camera effect is to simulate the effect of the human eye see, with the human eye see the world is the same, near large far small.
** Use: ** Most scenes are suitable for perspective projection cameras, because the effect is the same as the real world observation;
PerspectiveCamera: var camera = new THREE.PerspectiveCamera(fov, aspect, near, far)
parameter | introduce |
---|---|
fov | Field: Indicates the field of view that the camera can see. The default value 50 is recommended |
aspect | Specify the rendering results the ratio of horizontal and vertical direction length, recommended default values for the ratio of high to width of the window, the window. The innerWidth/window. The innerHeight, if the proportion set wrong, will find that renders the picture feel tension or compression. |
near | Close render distance: Specifies how close to the camera to start rendering. The recommended default is 0.1 |
far | Remote distance: Specifies how far the camera can see from its location. A remote distance in a scene that is too small will not be rendered. Too much will waste resources and affect performance. |
Near-end rendering distance and far-end distance: these two are the range of scene content that can be seen by the camera. Only the distance from the camera is greater than near value, less than FAR value, and within the camera’s viewing Angle, can be projected by the camera.
var camera = new THREE.PerspectiveCamera(
75.window.innerWidth / window.innerHeight,
0.1.1000
);// Create perspective projection camera
// Set the camera position
camera.position.x = 5;
camera.position.y = 10;
camera.position.z = 10;
// The above Settings can be abbreviated as:
camera.position.set(5.10.10);
Copy the code
OrthographicCamera
** Features: ** Orthogonal projection is the same size, parallel lines in three-dimensional space, projection to two-dimensional space must also be parallel.
** Uses: ** is generally used in drawing, modeling and other aspects, convenient to observe the size proportion between models.
OrthographicCamera(left,right, top,bottom, near, far);
parameter | introduce |
---|---|
left | The left end of the space that can be rendered |
right | The right end of the space that can be rendered |
top | Upper end of the space that can be rendered |
bottom | The lower end of the space that can be rendered |
near | The near end of the space that can be rendered based on where the camera is located |
far | The far end of the space that can be rendered based on the location of the camera |
The above six parameters specify the position of the camera’s viewing body on the left, right, up, down, front and back six surfaces. The area enclosed by these six projection surfaces is the visible area of the camera’s projection. In three dimensions, only objects in this region are visible to the camera.
var camera = new THREE.OrthographicCamera(-2.2.1, -1.1.10); // Create an orthogonal projection camera
// Set the camera position
camera.position.x = 5;
camera.position.y = 10;
camera.position.z = 10;
// The above Settings can be abbreviated as:
camera.position.set(5.10.10);
Copy the code
Contrast between orthogonal projection and perspective projection:
The image on the left is an orthogonal projection, in which the light reflected from an object is projected parallel to the screen, always of the same size, so objects near and far have the same size.
The picture on the right is a perspective projection, which is consistent with our usual feeling of seeing things.
3. Renderer
The renderer’s job is to render the image taken by the camera in the browser. The renderer determines what elements of the page the rendered results should be drawn on, and how they should be drawn.
There are many types of renderers in three. js, such as webGLRenderer, canvasRenderer, SVGRenderer, and usually webGLRenderer is used.
Create WebGLRenderer: var renderer = new therr.webglrenderer ();
After creating the renderer, we need to call the render method to render the scene and camera together, that is, call the render method: renderer.render(scene,camera)
var renderer = new THREE.WebGLRenderer(); // Create a WebGL renderer
renderer.setSize(window.innerWidth, window.innerHeight); // Set render length and width by calling setSize() (set renderer to full screen)
document.body.appendChild(renderer.domElement); // Display the rendered results on the page
renderer.render(scene, camera); // Combine the scene with the camera to render, using the camera to take the scene at the moment (the last step)
Copy the code
Description:
- The setSize() method sets the render length and width.
- Renderer’s domElement represents the canvas in the renderer, and all renderings are drawn on domElement, so appendChild means attach this domElement below the body, This way the rendered results can be displayed on the page.
- Passing our scene and camera in the Render () method is like passing a negative of the scene taken by the camera, which renders the image to our canvas.
These are the Three elements (scene, camera and renderer) for 3D drawing in Three.js. Only by using these Three elements can we render the scene to a web page using the camera.
Summary: scene, camera, renderer
** scene: ** is a three-dimensional space, used to store an object container, we can put the needed objects into the scene, such as apples, grapes. At the same time, objects themselves manage their position in the scene.
** camera: the function of ** camera is to face the scene, take a suitable scene in the scene, take it down.
** Renderer: ** Renderer is used to take pictures taken by the camera and display them in the browser.
The relationship between scene, camera and renderer is shown below:
8. Basic elements of Three.js
Think: We have scenes, cameras, renderers, what else do we need to display 3D images?
This photo can basically illustrate our 3D design mode of Three.js: after we have a scene, we need to put an object (subject) into it. Once we have an object we need to set up at least one light source so that we can see the object. Finally, what is presented to the customer is a series of animations generated by the continuous playback of the photos taken by the camera. The parameters, position and Angle of the camera directly affect the pictures we take.
** Conclusion: ** We need to place: object (subject), light source in the scene to show the 3D image.
Basic elements of Three.js:
- Object (subject)
- Geometry model
- Material
- Mesh
- The light source
9. Three.js design mode for creating objects (shot objects)
In the computer world, the 3D world is composed of points. Two points can form a straight line, and Three points that are not on a straight line can form a triangular surface. In three.js, any object (shooting object) is structured into small triangles. A small triangle can be used as the minimum unit of structure in both 2d and 3D graphics. And the structure is a grid of our subjects.
Grid structure of two-dimensional plane:
Three-dimensional sphere grid structure:
It can be seen that triangle is the minimum segmentation unit in three. js, which is the Mesh structure model. We usually call this Mesh model Mesh model, which is the most widely used model in 3D development.
Conclusion: The common way to draw 3D models is to use a grid of triangles to simulate them, as shown in the picture below. When enough triangles are used, the rabbit’s body looks smooth enough to be close to the real rabbit. The famous Stanford rabbit model uses 69,451 triangles.
Of course, having a grid structure is not enough. Just like the human body, because the grid structure is like a skeleton, it needs material on its exterior. A material is the texture (skin) of an object that determines the appearance of the geometry.
10. Basic Elements in Three.js: Geometry Model
In three.js, we preset some 2d and 3D geometry models for us
Two-dimensional geometry model:
Geometry of PlaneGeometry
Online example: www.webgl3d.cn/threejs/doc…
CircleGeometry
Online example: www.webgl3d.cn/threejs/doc…
RingGeometry
Online example: www.webgl3d.cn/threejs/doc…
3d geometry model:
BoxGeometry
Online example: www.webgl3d.cn/threejs/doc…
SphereGeometry
Online example: www.webgl3d.cn/threejs/doc…
CylinderGeometry
Online example: www.webgl3d.cn/threejs/doc…
TorusGeometry
Online example: www.webgl3d.cn/threejs/doc…
TubeGeometry
Online example: www.webgl3d.cn/threejs/doc…
…
The geometry model mentioned above is part of the built-in geometry in three. js. When we use these geometry, we only need to instantiate (create) the corresponding geometry object.
Example: Instantiate a cube geometry
var geometry = new THREE.BoxGeometry(1.1.1); // Create a cube with a length, width, and height of 1 unit
Copy the code
But having such a mesh geometry is not enough. The next step is to add a material (skin) to the geometry.
11. Basic elements in Three.js: Material
Three. Js also presets several material objects for us. Here are Three of them:
5. Meshbase material
A material that draws geometry in a simple shading (flat or wireframe) that is unaffected by light.
Online example: www.webgl3d.cn/threejs/doc…
Lambert mesh Material
A non – shiny surface material without specular highlights. This material does a good job of simulating some surfaces (such as untreated wood or stone), but not glossy surfaces with specular highlights (such as painted wood).
Online example: www.webgl3d.cn/threejs/doc…
Normal mesh Material
An RGB color material
Online example: www.webgl3d.cn/threejs/doc…
Special note: we can overlay multiple materials in the same grid structure.
var materialBasic = new THREE.MeshBasicMaterial({
color: 0xffffff./ / white
wireframe: true // // Whether to render geometry as wireframes, default is false (that is, as flat polygons)
}); // Create the base mesh material
var materialNormal = new THREE.MeshNormalMaterial(); // Create a normal mesh material
Copy the code
12. Basic elements in Three.js: Mesh
Once we have the geometry model and the material, we need to combine the two through a Mesh to create the object we are shooting.
There are two different shooting object constructors:
new THREE.Mesh(geometry, material)
THREE.SceneUtils.createMultiMaterialObject(geometry,[materials...] )
The first parameter represents the shape of the object and the second parameter represents the material of the object.
The above two methods are both ways to create objects. The first parameter is the Geometry model, and the only difference is the second parameter. The former can only be created with one material, while the latter can be created with multiple materials (passing in an array of multiple materials).
// Create a mesh that wraps the material around the geometry
var cube = new THREE.Mesh(geometry, material);
// Create multiple meshes to wrap the material around the geometry model
var cube = THREE.SceneUtils.createMultiMaterialObject(geometry, [
materialBasic,
materialNormal
]);
// Make the camera look at the position of the object (subject) (by default, the camera points to the origin of the 3d coordinate system).
camera.lookAt(cube.position);
Copy the code
Now that we have a subject, we need to add our subject (object) to the scene, just as we would with merchandise, by placing our merchandise in the space.
In three.js, adding an object to a scene can be done directly by calling the Add method on the scene object.
// Add the grid to the scene
scene.add(cube);
Copy the code
An object can be seen by the human eye because it emits light from its own material, without external light sources. The other is that the material itself does not emit light and needs to reflect light from the environment. For objects that cannot emit light on their own, light sources need to be added to the scene to achieve visual effects.
13. Basic elements in Three.js: Light
There are many different types of light sources that can be created in three.js:
AmbientLight
Ambient light is a basic light source that uniformly illuminates all objects in the scene. Ambient light has no specific source direction and does not create shadows.
SpotLight
A spotlight (similar to a flashlight, stage spotlight) is emitted from a point in one direction, along a cone, and the further away it is from the light, the greater its size. This light source creates shadows.
Parallel light
Parallel light is light emitted in a particular direction. This light behaves as if it were infinitely far away, and the rays coming from it are all parallel. Parallel light is often used to simulate the effect of sunlight; The sun is far enough away that we can think of it as being infinitely far away, so we think of light coming from the Sun as being parallel. This light source creates shadows.
Create a light source instance in three.js:
// Create light source
var spotLight = new THREE.SpotLight(0xffffff);
// Set the light position
spotLight.position.set(0.20.20);
// Set the intensity of light source
spotLight.intensity = 5;
// Add light to the scene
scene.add(spotLight);
Copy the code
- The position.set() method sets the position in three-dimensional space.
- The intensity attribute sets the intensity of the light source. The default value is 1.
14. Add a 3d coordinate object to three. js
To facilitate viewing the 3D image, add a 3D coordinate object
// Add a 3D coordinate object to facilitate viewing 3D images
var axes = new THREE.AxisHelper(4); // Set the coordinate axis length to 4
// Add a 3d coordinate system to the scene
scene.add(axes);
Copy the code
15. Use three. js to display 3D graphics on the screen:
- Create a three-dimensional Scene;
- Create a Camera, determine an observation point, and set the Camera observation direction and Angle;
- Create the renderer, set the length and width of the renderer, and display the render results on the page;
- Create objects (geometry, material, grid), light sources (set light location) and add them to the scene;
- Finally, render the scene and camera to the page through the renderer.
Use three. js to implement a basic case
<html>
<head>
<title>Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<! -- introducing three. Js -->
<script src="https://cdn.bootcss.com/three.js/r83/three.min.js"></script>
<script>
// create a scene
var scene = new THREE.Scene();
// create camera (perspective projection camera)
var camera = new THREE.PerspectiveCamera(
50.// Camera field
window.innerWidth / window.innerHeight, // The ratio of horizontal to vertical lengths
0.1.// Close render distance
1000 // Remote render distance
);
// 2.1 Setting the camera position
// camera.position.x = 5;
// camera.position.y = 10;
// camera.position.z = 10;
// 2.1 Setting the camera position
camera.position.set(5.10.10);
// create renderer
var renderer = new THREE.WebGLRenderer();
// 3.1 Set the renderer size (length and width) (set the renderer to full screen)
renderer.setSize(window.innerWidth, window.innerHeight);
// 3.2 Render the result on the page
document.body.appendChild(renderer.domElement);
// Create geometry model (cubic geometry)
var geometry = new THREE.BoxGeometry(4.4.4);
// create material (base mesh material and Normal mesh material)
// 5.1 Create the base mesh material
var materialBasic = new THREE.MeshBasicMaterial({
color: 0xffffff./ / white
// color: 0x00ff00, // green
wireframe: true // Whether to render geometry as wireframes, default is false (i.e., as flat polygons)
});
// 5.2 Create a normal mesh material
var materialNormal = new THREE.MeshNormalMaterial();
// Create multiple meshes (because there are multiple materials)
// The first parameter is the geometry model, and the second parameter is the material
var cube = THREE.SceneUtils.createMultiMaterialObject(geometry, [
materialBasic,
materialNormal
]);
// 6.1. Add the grid to the scene
scene.add(cube);
// 6.2 Let the camera look at the position of the object (subject) (by default, the camera points to the origin of the 3d coordinate system).
camera.lookAt(cube.position);
// Create a light source
var spotLight = new THREE.SpotLight(0xffffff);
// 7.1 Setting the Light Source Position
spotLight.position.set(0.20.20);
7.2 Set the intensity of the light source. The default value is 1
spotLight.intensity = 5;
// 7.3 Add light source to scene
scene.add(spotLight);
// Add a 3D coordinate object for easy viewing of 3D images
var axes = new THREE.AxisHelper(6);
scene.add(axes);
// 9. Combine the scene with the camera for rendering
renderer.render(scene, camera);
</script>
</body>
</html>
Copy the code
17. Animation in Three.js
The animation principles
Animation is actually an illusion created by a series of pictures playing at a certain frequency for a certain amount of time.
An important characteristic of the eye is visual inertia, that is, once a light image is formed on the retina, the vision will maintain the perception of the light image for a limited time, this physiological phenomenon is called visual persistence. When the human eye looks at an object, the image is imaged on the retina and sent to the brain by the optic nerve to sense the image of the object. Frame by frame images are fed into the brain, which then connects them to create an animation. For light stimuli of moderate intensity, the visual duration is about 0.1 to 0.4 seconds.
In order for animations to transition in a consistent, smooth manner, we typically render animations at 60 frames per second or more.
Create the animation
Use the requestAnimationFrame() method in three.js to create the animation. Because the animation needs to play at a certain frequency, you need to create a looping render function that will be called at the end.
// Animation loop render function
function animate() {
// loop over the function
requestAnimationFrame(animate);
// (Attributes that need to be updated here... The code)
// The renderer combines the scene and camera to render
renderer.render(scene, camera);
}
Copy the code
This is done by updating and rendering properties within the looping function body and letting the browser control the updating of animation frames.
Animate (based on original code)
RequestAnimationFrame (animate) enables the browser to invoke animate methods every time the page is updated. And each call, the properties of the L cube will be changed accordingly: each call will rotate the X axis and Y axis 0.01 radian than the previous one, and render it to the canvas.
function animate() {
// loop over the function
requestAnimationFrame(animate);
With each animate call, the grid is rotated 0.01 radians more than the last time
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// The renderer combines the scene and camera to render
renderer.render(scene, camera);
};
animate();
Copy the code
View animation effects (complete code for animation version)
<html>
<head>
<title>Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<! -- introducing three. Js -->
<script src="https://cdn.bootcss.com/three.js/r83/three.min.js"></script>
<script>
// create a scene
var scene = new THREE.Scene();
// create camera (perspective projection camera)
var camera = new THREE.PerspectiveCamera(
50.// Camera field
window.innerWidth / window.innerHeight, // The ratio of horizontal to vertical lengths
0.1.// Close render distance
1000 // Remote render distance
);
// 2.1 Setting the camera position
// camera.position.x = 5;
// camera.position.y = 10;
// camera.position.z = 10;
// 2.1 Setting the camera position
camera.position.set(5.10.10);
// create renderer
var renderer = new THREE.WebGLRenderer();
// 3.1 Set the renderer size (length and width) (set the renderer to full screen)
renderer.setSize(window.innerWidth, window.innerHeight);
// 3.2 Render the result on the page
document.body.appendChild(renderer.domElement);
// Create geometry model (cubic geometry)
var geometry = new THREE.BoxGeometry(4.4.4);
// create material (base mesh material and Normal mesh material)
// 5.1 Create the base mesh material
var materialBasic = new THREE.MeshBasicMaterial({
color: 0xffffff./ / white
wireframe: true // Whether to render geometry as wireframes, default is false (i.e., as flat polygons)
});
// 5.2 Create a normal mesh material
var materialNormal = new THREE.MeshNormalMaterial();
// Create multiple meshes (because there are multiple materials)
// The first parameter is the geometry model, and the second parameter is the material
var cube = new THREE.Mesh(geometry, materialNormal);
// 6.1 Make the camera look at the position of the object (subject) (by default, the camera points to the origin of the 3D coordinate system).
camera.lookAt(cube.position);
6.2. Add the grid to the scene
scene.add(cube);
// Create a light source
var spotLight = new THREE.SpotLight(0xffffff);
// 7.1 Setting the Light Source Position
spotLight.position.set(0.20.20);
7.2 Set the intensity of the light source. The default value is 1
spotLight.intensity = 5;
// 7.3 Add light source to scene
scene.add(spotLight);
// Add a 3D coordinate object for easy viewing of 3D images
var axes = new THREE.AxisHelper(6);
scene.add(axes);
// create an animation loop render function
function animate() {
// 9.1 Loop calling functions
requestAnimationFrame(animate);
With each animate call, the grid is rotated 0.01 radians more than the last time
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// 3.3 Combine scene and camera for rendering, that is, take the scene at the moment with camera
renderer.render(scene, camera);
};
// Call the animation function
animate();
</script>
</body>
</html>
Copy the code
18. Introduction to Three. Js plug-ins
Sometimes, we need to adjust the position or size of the model, and we need to go to the scene every time for debugging, which is not very convenient and intuitive. Is there a plug-in that can solve this problem?
1, dat. GUI
Dat.GUI link: github.com/dataarts/da…
Dat.GUI is a lightweight graphical user interface plug-in for modifying variables in JavaScript that makes it easy to create interface components that can change code variables for some real-time interaction.
Use dat. GUI
1. Introduce the DAT.GUI plug-in
<script src="https://cdn.bootcss.com/dat-gui/0.7.1/dat.gui.min.js"></script>
Copy the code
2. Define an object in which to set some data we need to modify:
// Define the object and set the data to be modified
var controls = {
positionX:0.positionY:0.positionZ:0
};
Copy the code
3. Instantiate the dat.GUI object, add the configuration that needs to be modified to the object, and listen for the change callback:
// Instantiate the dat.GUI object
var gui = new dat.GUI();
// Add the configuration to the dat.GUI object
//gui.add(Modified configuration object, modified data name in the configuration object, modified start point of data boundary, modified end point of data boundary)
// onChange: The onChange method is triggered whenever data changes
gui.add(controls, "positionX", -10.10).onChange(updatePosition);
gui.add(controls, "positionY", -1.1).onChange(updatePosition);
gui.add(controls, "positionZ", -1.1).onChange(updatePosition);
// Define the update model position function
function updatePosition() {
// Sets the position of the grid in the page
cube.position.set(controls.positionX, controls.positionY, controls.positionZ);
}
Copy the code
This way, every time we change the value in the object, the updatePosition callback is triggered to update the position of the model.
Add dat.GUI plug-in after the complete code
<html>
<head>
<title>Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<! -- introducing three. Js -->
<script src="https://cdn.bootcss.com/three.js/r83/three.min.js"></script>
<! Dat. GUI -->
<script src="https://cdn.bootcss.com/dat-gui/0.7.1/dat.gui.min.js"></script>
<script>
// create a scene
var scene = new THREE.Scene();
// create camera (perspective projection camera)
var camera = new THREE.PerspectiveCamera(
50.// Camera field
window.innerWidth / window.innerHeight, // The ratio of horizontal to vertical lengths
0.1.// Close render distance
1000 // Remote render distance
);
// 2.1 Setting the camera position
// camera.position.x = 5;
// camera.position.y = 10;
// camera.position.z = 10;
// 2.1 Setting the camera position
camera.position.set(5.10.10);
// create renderer
var renderer = new THREE.WebGLRenderer();
// 3.1 Set the renderer size (length and width) (set the renderer to full screen)
renderer.setSize(window.innerWidth, window.innerHeight);
// 3.2 Render the result on the page
document.body.appendChild(renderer.domElement);
// 10.1 Defining objects and setting data to be modified
var controls = {
positionX: 0.positionY: 0.positionZ: 0
};
// Create geometry model (cubic geometry)
var geometry = new THREE.BoxGeometry(4.4.4);
// create material (base mesh material and Normal mesh material)
// 5.1 Create the base mesh material
var materialBasic = new THREE.MeshBasicMaterial({
color: 0xffffff./ / white
wireframe: true // Whether to render geometry as wireframes, default is false (i.e., as flat polygons)
});
// 5.2 Create a normal mesh material
var materialNormal = new THREE.MeshNormalMaterial();
// Create multiple meshes (because there are multiple materials)
// The first parameter is the geometry model, and the second parameter is the material
var cube = THREE.SceneUtils.createMultiMaterialObject(geometry, [
materialBasic,
materialNormal
]);
// 6.1 Make the camera look at the position of the object (subject) (by default, the camera points to the origin of the 3D coordinate system).
camera.lookAt(cube.position);
6.2. Add the grid to the scene
scene.add(cube);
// Create a light source
var spotLight = new THREE.SpotLight(0xffffff);
// 7.1 Setting the Light Source Position
spotLight.position.set(0.20.20);
7.2 Set the intensity of the light source. The default value is 1
spotLight.intensity = 5;
// 7.3 Add light source to scene
scene.add(spotLight);
// Add a 3D coordinate object for easy viewing of 3D images
// var axes = new THREE.AxisHelper(6);
// scene.add(axes);
// create an animation loop render function
function animate() {
// 9.1 Loop calling functions
requestAnimationFrame(animate);
With each animate call, the grid is rotated 0.01 radians more than the last time
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// 3.3 Combine scene and camera for rendering, that is, take the scene at the moment with camera
renderer.render(scene, camera);
};
// Call the animation function
animate();
// 10.2 Instantiating the dat.GUI object
var gui = new dat.GUI();
// 10.3 Add the configuration to the Dat.GUI object
gui.add(controls, "positionX", -10.10).onChange(updatePosition);
gui.add(controls, "positionY", -10.10).onChange(updatePosition);
gui.add(controls, "positionZ", -1.1).onChange(updatePosition);
// 10.4 Define the update model location function
function updatePosition() {
cube.position.set(controls.positionX, controls.positionY, controls.positionZ);
}
</script>
</body>
</html>
Copy the code
In Three.js, the most frequent problems are performance problems, so we need to constantly check the performance of the current three. js. Is there a plug-in to help us detect performance problems of Three.js?
Without a doubt, the higher the frame count, the better the picture will feel. So most games will have more than 30 FPS. To monitor FPS and see where your application is using a lot of CPU time, you need to learn about performance monitors.
2, stats. Js
About performance: In the 3D world, frames are often used to test whether an application has a performance bottleneck.
**stats.js link: **github.com/mrdoob/stat…
Stats.js is a JavaScript performance monitor that helps monitor the performance of your code, primarily for detecting the number of frames an animation is running in.
-
FPS: The number of times a graphics processor can refresh Per Second, usually expressed as Frames Per Second, the higher the number, the better.
-
Milliseconds (MS) : The number of MS milliseconds required to render a frame, the smaller the better.
-
MB: MB bytes of allocated memory
Using the stats. Js
- The introduction of
<script src="http://www.wjceo.com/lib/js/libs/stats.min.js"></script>
Copy the code
- instantiation
stats
Object and then put the generated object insidedom
Add to the page.
var stats = new Stats();
document.body.appendChild(stats.dom);
Copy the code
- in
requestAnimationFrame
Update each render time inside the callback:
function animate() {
requestAnimationFrame(animate); // loop over the function
stats.update(); // Update the performance plug-in
renderer.render( scene, camera ); // Render the interface
}
animate();
Copy the code
Complete code after adding stats. Js plug-in
<html>
<head>
<title>Cube</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<! -- introducing three. Js -->
<script src="https://cdn.bootcss.com/three.js/r83/three.min.js"></script>
<! Dat. GUI -->
<script src="https://cdn.bootcss.com/dat-gui/0.7.1/dat.gui.min.js"></script>
<! Stats.js -->
<script src="http://www.wjceo.com/lib/js/libs/stats.min.js"></script>
<script>
// create a scene
var scene = new THREE.Scene();
// create camera (perspective projection camera)
var camera = new THREE.PerspectiveCamera(
50.// Camera field
window.innerWidth / window.innerHeight, // The ratio of horizontal to vertical lengths
0.1.// Close render distance
1000 // Remote render distance
);
// 2.1 Setting the camera position
// camera.position.x = 5;
// camera.position.y = 10;
// camera.position.z = 10;
// 2.1 Setting the camera position
camera.position.set(5.10.10);
// create renderer
var renderer = new THREE.WebGLRenderer();
// 3.1 Set the renderer size (length and width) (set the renderer to full screen)
renderer.setSize(window.innerWidth, window.innerHeight);
// 3.2 Render the result on the page
document.body.appendChild(renderer.domElement);
// There is also step 3.3 (which will be removed later), which combines the scene with the camera for rendering, using the camera to capture the scene at the moment
// renderer.render(scene, camera);
// 10.1 Defining objects and setting data to be modified
var controls = {
positionX: 0.positionY: 0.positionZ: 0
};
// Create geometry model (cubic geometry)
var geometry = new THREE.BoxGeometry(4.4.4);
// create material (base mesh material and Normal mesh material)
// 5.1 Create the base mesh material
var materialBasic = new THREE.MeshBasicMaterial({
color: 0xffffff./ / white
wireframe: true // Whether to render geometry as wireframes, default is false (i.e., as flat polygons)
});
// 5.2 Create a normal mesh material
var materialNormal = new THREE.MeshNormalMaterial();
// Create multiple meshes (because there are multiple materials)
// The first parameter is the geometry model, and the second parameter is the material
var cube = THREE.SceneUtils.createMultiMaterialObject(geometry, [
materialBasic,
materialNormal
]);
// 6.1 Make the camera look at the position of the object (subject) (by default, the camera points to the origin of the 3D coordinate system).
camera.lookAt(cube.position);
6.2. Add the grid to the scene
scene.add(cube);
// Create a light source
var spotLight = new THREE.SpotLight(0xffffff);
// 7.1 Setting the Light Source Position
spotLight.position.set(0.20.20);
7.2 Set the intensity of the light source. The default value is 1
spotLight.intensity = 5;
// 7.3 Add light source to scene
scene.add(spotLight);
// Add a 3D coordinate object for easy viewing of 3D images
var axes = new THREE.AxisHelper(6);
scene.add(axes);
// instantiate the performance monitoring plug-in
var stats = new Stats();
// add the DOM generated by the stats object to the page (so that you can see the performance monitor in the page)
document.body.appendChild(stats.dom);
// create an animation loop render function
function animate() {
// 9.1 Loop calling functions
requestAnimationFrame(animate);
With each animate call, the grid is rotated 0.01 radians more than the last time
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
// 11.2 Update performance plug-ins
stats.update();
// 3.3 Combine scene and camera for rendering, that is, take the scene at the moment with camera
renderer.render(scene, camera);
};
// Call the animation function
animate();
// 10.2 Instantiating the dat.GUI object
var gui = new dat.GUI();
// 10.3 Add the configuration to the Dat.GUI object
gui.add(controls, "positionX", -10.10).onChange(updatePosition);
gui.add(controls, "positionY", -10.10).onChange(updatePosition);
gui.add(controls, "positionZ", -1.1).onChange(updatePosition);
// 10.4 Define the update model location function
function updatePosition() {
cube.position.set(controls.positionX, controls.positionY, controls.positionZ);
}
</script>
</body>
</html>
Copy the code