introduction
This article mainly explains the relevant concepts of Three.js and helps readers develop a relatively complete understanding of Three.js and related knowledge.
The web has developed rapidly in recent years. With the popularity of HTML5, the performance capabilities of web pages are becoming more and more powerful. There are already many complex animations and exquisite effects on the web page.
But people are always greedy. So, what else can be done above this? One of them is to draw high-performance 3D graphics in web pages through WebGL.
OpenGL, WebGL to Three.js
Many people probably heard of OpenGL , which is the most commonly used cross-platform graphics library.
WebGL is a web-oriented graphics standard designed by OpenGL, providing a series of JavaScript APIs through which graphics rendering will be leveraged to achieve higher performance.
Three.js is an easy-to-use graphics library formed by encapsulating and simplifying the WebGL interface.
To put it simply: WebGL can be regarded as an interface provided by the browser. In JavaScript, these APIs can be used directly to draw 3D graphics; and Three.js helps us encapsulate these interfaces to be more useful.
Comparison of WebGL and Three.js
Since we have WebGL, why do we still need Three.js?
This is because the threshold for WebGL is relatively high and requires relatively more mathematical knowledge. Although WebGL provides a front-end API, WebGL and front-end development are essentially two different directions, and there is little overlap of knowledge. The relevance is that they are all on the web platform and they all use JavaScript. A front-end programmer may be familiar with analytical geometry, but there should be very few who are still familiar with linear algebra (for example, try to find an inverse transpose matrix?), not to mention that the physical significance of matrix operations is emphasized in use, which is also relatively missing in teaching.
Therefore, it is quite difficult for front-end engineers to get started with WebGL in a short time.
Therefore, Three.js has very good encapsulation of the interface provided by WebGL, simplifying many details and greatly reducing learning costs. And, there is little loss of flexibility in WebGL.
Therefore, starting with Three.js is worth recommending, which allows you to face most demand scenarios after a shorter study.
Three.js learning problems
Getting started with Three.js is relatively simple, but when we really learn, we will find an embarrassing problem: there is very little related learning materials.
Usually this popular library has very complete documents, and often the best way to learn from official documents or official introductory tutorials. But Three is not, its documentation is too concise for beginners.
However, the official provides a very rich variety of examples, and almost all the usages you need are reflected in a certain example. But these examples are not suitable for getting started, but are suitable for further learning after getting started.
Here are some relatively good tutorials:
Three.js Getting Started Guide
This is a good lightweight introductory tutorial for Three.js. The author has a very good writing style and the basic knowledge is explained concisely and easily understandable.
Three.js Development Guide (First Chinese Version)
Learning Three.js- Second Edition
Learning Three.js:The JavaScript 3D Library for WebGL is the few and best introductory book of Three.js, which explains the various functions of Three.js in a more comprehensive way.
If you have the ability, it is recommended to read the second edition of the English version, published in 2015, which is very small different from the current Three.js.
The Chinese version is translated from the first edition of the original book published in 2012. Most of the concepts are applicable, but many details have changed.
Three.js tutorial
This is a translation of a foreign tutorial, with a total of six articles . I don’t explain much, but it’s more about how to use each basic function. It is more suitable for students with some graphics foundation.
Of course, these materials are definitely not enough during the actual learning process. When encountering problems, you still have to check the materials yourself. However, I would like to remind you that Three.js is updated quite frequently, now it is the r80 version. Since r1 was released in April 2010, this is the 72nd version (some version numbers in the middle have been skipped). Therefore, some of the information found on the Internet may not be suitable for the current version , so you need to pay attention to the identification (the previously recommended information also has more or less such problems).
Some concepts in Three.js
To display 3D graphics on the screen, the idea is generally like this:
Building a three-dimensional space
In Three, it is called Scene (Scene) to select an observation point and determine the observation direction/angle, etc.
Three calls it the camera (Camera) to add objects for observation to the scene
There are many types of objects in Three, including Mesh, Line, Points, etc. They all inherit from the Object3D class renders the observed scene to a specified area on the screen.
Use Renderer in Three to do this
Let’s take a look at these concepts in Three in detail.
Scene
The scene is a container of all objects, and it also corresponds to the three-dimensional world we create.
Camera coordinate system
Camera is an observer in the three-dimensional world. In order to observe this world, we must first describe the position in space.
The common right-hand coordinate system is used in Three.
Three-dimensional projection
There are two types of cameras in Three, namely the orthographic projection camera THREE.Othographic Camera and the perspective projection camera THREE.Perspective Camera.
The difference between orthogonal projection and perspective projection is shown in the figure above. The left picture is an orthogonal projection. The light emitted by the object is projected parallel to the screen, and the squares far and near are the same size; the right picture is a perspective projection, which is large in the near and small in the far and small, which is in line with our usual feeling of looking at things.
Wikipedia: 3D projection
Orthogonal projection camera
Note: The "viewpoint" in the figure corresponds to Camera in Three.
Here we add a concept of visual body: visual body is a geometric body, only objects in visual body will be seen by us, and objects outside the visual body will be cut off. This is to remove unnecessary operations.
The view body of the orthographic projection camera is a cuboid. The constructor of OrthographicCamera is as follows: OrthographicCamera( left, right, top, bottom, near, far)
Camera itself can be regarded as a point, while left indicates the distance between the left plane and Camera in the left and right direction. The same applies to the other parameters. Therefore, the six parameters define the positions of the six faces of the viewing body respectively.
It can be approximately assumed that the objects in the viewing body are projected parallel to the near plane, and then the images on the near plane are rendered onto the screen.
Perspective projection camera
The perspective projection camera's viewing body is a four-edge platform, and its constructor is as follows: PerspectiveCamera( fov, aspect, near, far)
fov corresponds to the perspective in the figure, which is the angle between the upper and lower sides. aspect is the aspect ratio of the near plane. Adding the near-plane distance near and far-plane distance far, the only way to determine the visual scene.
Perspective projection cameras are very consistent with our usual feeling of watching things, so in most cases we use Perspective projection cameras to show 3D effects.
Objects
With a camera, you have to look at something, right? Add some objects to the scene.
There are many objects for display in Three, all of which are inherited from the Object3D class. Here we mainly look at Mesh and Points.
Mesh
We all know that in the computer world, an arc is connected by a finite line segment composed of finite points. When there are many lines, it looks like a smooth arc.
The three-dimensional model in computers is similar. The common practice is to describe it using a grid of triangles. We call this model the Mesh model.
This is the famous Stanford rabbit. Its position in 3D graphics is similar to that of Lena, a well-known field of digital image processing.
Look at this rabbit, as the number of triangles increases, its surface becomes smoother/accurate.
In Three, the constructor of Mesh is as follows: Mesh(geometry, material)
geometry is its shape, material is its material.
Not only Mesh, these two properties are used to create many objects. Let’s take a look at these two important attributes.
Geometry
Geometry, shape, is quite intuitive. Geometry uses the model to store the set of points and the relationship between points (which points form a triangle) to achieve the purpose of describing the shape of an object.
Three provides many basic shapes such as cubes (actually cuboids), planes (actually rectangles), spheres, circles, cylinders, and round tables;
You can also construct shapes by defining the position of each point yourself;
For more complex shapes, we can also import them through external model files.
Material
Material, material, this is not as intuitive as the shape.
Material is actually a collection of all visual attributes except shape of the object surface, such as color, texture, smoothness, transparency, reflectivity, refractive index, and luminosity.
Here we will talk about the relationship between material, map and texture.
The material has been mentioned above, and it includes maps and others.
The stickers are actually 'paste' and 'paste', which includes the pictures and where the pictures should be posted.
As for the texture, it is actually a 'picture'.
Three offers a variety of materials to choose from, and can freely choose diffuse/specular reflection and other materials.
Points
After talking about Mesh, let’s take a look at another Object - Points.
Points is actually a collection of a bunch of points. It was called ParticleSystem for a long time before. It was renamed PointCloud in the r68 version, and it was renamed Points in the r72 version. The name change is mainly because Mr.doob believes that particle systems should be a complete system that includes the processing of particles and related physical properties, while Points in Three are much simpler. So eventually this class is named Points.
The typical effect that Points can be used to achieve is this: Official example
Light
God said: There must be light!
The light and shadow effect is an important factor that enriches the picture.
Three provides a variety of light sources including ambient light AmbientLight, point light source PointLight, spotlight SpotLight, directional light DirectionalLight, hemisphere light Hemisphere Light and other light.
Just add the required light source to the scene.
Renderer
Various objects are built in the scene, light, and cameras that observe objects, it is time to render what you see onto the screen. That's what Render does.
Renderer binds a canvas object and can set properties such as size, default background color, etc.
Call the render function of Renderer, pass in scene and camera, and you can render the image into canvas.
Make the picture move
Now, a static picture can be obtained, how can it move?
A very simple idea is to change the position, angle and various properties of the object in the scene, and then call the render function to render.
So how do you determine the timing of re-rendering?
HTML5 provides us with requestAnimFrame, which automatically calls the passed function before each page repaint.
If we render this at the beginning:
function render(){ renderer.render(scene, camera);}Just change it to this:
function render(){ requestAnimationFrame(render); object.position.x += 1; renderer.render(scene, camera);}object can move!
Give a chestnut
Let’s use a simple example to sort out this process.
First, write a page with Canvas elements.
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>cube</title> <script src="http://sqimg.qq.com/qq_product_operations/mma/javanli_test/lib/three.min.js"></script> <style type="text/css"> html, body { margin: 0; padding: 0; } #three_canvas { position: absolute; width: 100%; height: 100%; } </style></head><body> <canvas id="three_canvas"></canvas></body></html>Let's do the Javascript part below
First initialize Renderer
function initRenderer() { width = document.getElementById('three_canvas').clientWidth; height = document.getElementById('three_canvas').clientHeight; renderer = new THREE.WebGLRenderer({ //Bind Canvas to renderer canvas: document.getElementById('three_canvas') }); renderer.setSize(width, height); //Set the rendering size to the same as Canvas renderer.setClearColor(0xFFFFFF, 1.0);//Set the default color and transparency}Initialization scenario:
function initScene() { scene = new THREE.Scene();}Initialize the camera:
function initCamera() { //Simple orthogonal projection camera, facing the center of the viewport, the viewport size is the same as the Canvas size. camera = new THREE.OthographicCamera(width / -2, width / 2, height / 2, height / -2, 1, 1000); //Set the camera position camera.position.x = 0; camera.position.y = 0; camera.position.z = 200; //Set the camera's upward direction camera.up.x = 0; camera.up.y = 1; camera.up.z = 0; //Set the camera's focus position (actually to determine a direction) camera.lookAt({ x: 0, y: 0, z: 0 });}To uniquely determine the position and direction of a camera, the three attributes of position, up, and lookAt are indispensable.
Here we have created an orthogonal projection camera. Here I keep the view size consistent with the screen resolution just for convenience, so that a unit length in the coordinate system corresponds to a pixel of the screen.
We place the camera on the Z axis, facing the coordinate origin, and the upper direction of the camera is the Y axis. Note that the direction of up and the direction of lookAt must be perpendicular (you will know if you compare yourself to your own head).
Here is a cube added to the scene:
function initObject() { //Create a cube with a side length of 100 var geometry = new THREE.CubeGeometry(100, 100, 100); object = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial()); scene.add(object);}Note that we use the normal material MeshNormalMaterial , so that the color of each face of the cube is related to the direction facing this face, making it easier to observe/debug.
In this simple demo, I don't plan to add light and shadow effects, and the normal material does not respond to light.
Finally, create an animation loop
function render() { requestAnimationFrame(render); object.rotation.x += 0.05; object.rotation.y += 0.05; renderer.render(scene, camera);}Each repaint makes the cube rotate a little bit.
When the page is loading, just call the previous functions
function threeStart() { initRenderer(); initCamera(); initScene(); initObject(); render();}window.onload = threeStart();The complete demo looks like this:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>cube</title> <script src="http://sqimg.qq.com/qq_product_operations/mma/javanli_test/lib/three.min.js"></script> <style type="text/css"> html, body { margin: 0; padding: 0; } #three_canvas { position: absolute; width: 100%; height: 100%; } </style></head><body><canvas id="three_canvas"></canvas><script> var renderer, camera, scene, light, object; var width, height; function initRenderer() { width = document.getElementById('three_canvas').clientWidth; height = document.getElementById('three_canvas').clientHeight; renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('three_canvas') }); renderer.setSize(width, height); renderer.setClearColor(0xFFFFF, 1.0); } function initCamera() { camera = new THREE.OthographicCamera(width / -2, width / 2, height / 2, height / -2, 1, 1000); camera.position.x = 0; camera.position.y = 0; camera.position.z = 200; camera.up.x = 0; camera.up.y = 1; camera.up.z = 0; camera.lookAt({ x: 0, y: 0, z: 0 }); } function initScene() { scene = new THREE.Scene(); } function initObject() { var geometry = new THREE.CubeGeometry(100, 100, 100); object = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial()); scene.add(object); } function render() { requestAnimationFrame(render); object.rotation.x += 0.05; object.rotation.y += 0.05; renderer.render(scene, camera); } function threeStart() { initRenderer(); initCamera(); initScene(); initObject(); render(); } window.onload = threeStart();</script></body></html>After saving as html, open it, such a rotating cube will be displayed in the center of the screen.
summary
That’s all for the introduction of Three.js. This article basically mentions important components in Three. In fact, there are many things I want to summarize, but writing them in this article may seem cumbersome. The original intention of this article is to let readers have an intuitive and general understanding of Three.js after reading it, and do not intend to involve too many details.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.