Introduction
本文主要是讲解Three.js的相关概念,帮助读者对Three.js以及相关知识形成比较完整的理解。
The web has been developing rapidly in recent years. With the popularization of HTML5, the performance of Web pages is becoming more and more powerful. The page has been able to make a lot of complex animations, beautiful effects.
However, people are always greedy. So what can be done on top of this? One is to draw high-performance 3D graphics in Web pages with WebGL.
Opengl,webgl to Three.js
OpenGL is something that many people have heard about, which is the most common cross-platform graphics library.
WebGL is a web-oriented graphics standard based on OpenGL design and provides a series of JavaScript APIs that enable graphical rendering using graphics hardware for high performance.
Three.js is an easy-to-use graphics library that is formed by the encapsulation and simplification of the WebGL interface.
The simple point of view: WebGL can be seen as a browser to provide us with the interface, in JavaScript can be directly used in these APIs to draw 3D graphics, and three.js is on these interfaces to help us encapsulate better use some.
WebGL vs. Three.js
Now that we have WebGL, why do we need three.js?
This is because the WEBGL threshold is relatively high and requires relatively more mathematical knowledge. While WebGL provides a front-end API, it is essentially two different directions for WEBGL and front-end development, with little knowledge overlap. Relevance only they are on the web platform, all with JavaScript. A front-end programmer may also be familiar with analytic geometry, but there should be few that are familiar with linear algebra (for example, try a reverse matrix). , not to mention the physical significance of matrix operations in the use, which is also relatively absent in teaching.
Therefore, it is difficult for front-end engineers to get started with WebGL in a short time.
As a result, Three.js has a very good encapsulation of the interfaces provided by WEBGL, simplifying many details and greatly reducing the cost of learning. And, there's almost no loss of webgl flexibility.
Therefore, it is recommended to start with Three.js, which allows you to face most of the demand scenarios after a short study.
The study problem of Three.js
Three.js is relatively simple to get started with, but when we really go to school, we find a very awkward question: there are few related learning materials.
Often this popular library has very good documentation, and many times it is best to follow the official documentation or the official introductory tutorials. But three is not, its documentation is too concise for beginners.
But the official offers a very rich examples, and almost all the usage you need is reflected in some example. But these example are not suitable for getting started, but are suitable for further study after getting started.
Some relatively good tutorials are recommended here:
Three.js Getting Started Guide
This is a good three.js lightweight Introductory tutorial , the author is very good at writing, the basic knowledge is simple and easy to understand.
Three.js Development Guide (First edition Chinese version)
Learning Three.js-second Edition
Learning Three.js:The JavaScript 3D Library for WebGL is now a few and the best three.js introductory book, a more comprehensive explanation of the various functions of three.js.
If you have the ability, it is recommended to read the second edition of the English version, published in 2015, and the current three.js difference is very small.
Since the first edition of the original book, published in 2012, most of the concepts are applicable, but many of the details have changed.
Three.js Getting Started Tutorial
This is a translation of a foreign tutorial, a total of six articles . The explanation is not much, more is to show each basic function how to use. More suitable for students with some graphic basis.
Of course, the actual learning process of these materials is certainly not enough, encountered problems or to find their own information. But here's to remind you, Three.js's update is quite frequent, now is the R80 version, since the release of the R1 in April 2010, this is the 72nd version (the middle of the version number skipped). Therefore, the information found on the Internet may not be suitable for the current version , need to pay attention to screening (the previously recommended information is more or less such a problem).
Some concepts in the Three.js
To display 3D graphics on the screen, the idea is basically this:
- Building a three-dimensional space
- Select an observation point and determine the viewing direction/angle, etc.
- Three called cameras (camera )
- Adding objects for observation in the scene
- There are many kinds of objects in three, including Mesh,line,points, and they all inherit from Object3d class.
- Renders the observed scene to a specified area on the screen
- Use renderer to complete this work in three
Here's a look at these concepts in three.
Scene
The scene is a container for all objects, and also corresponds to the three-dimensional world we create.
Camera coordinate system
Camera is the observer in the three-dimensional world, in order to observe the world, we first describe the position in space.
The three uses a common right-handed coordinate system for positioning.
Three-dimensional projection
There are two types of cameras in the three, namely the positive projection camera Three.orthographiccamera and the perspective projection camera Three.perspectivecamera.
The difference between orthographic projection and perspective projection is as shown, the left image is orthogonal projection, the light emitted by the object is projected to the screen in parallel, the blocks are the same size, and the right image is the perspective projection, which is near large and small, in line with the feeling of seeing things in our usual way.
Wikipedia: three-dimensional projection
Orthographic projection Camera
Note: the "viewpoint" in the figure corresponds to the camera in the three.
The concept of a visual body is added here: The visual body is a geometry, and only objects in the scene will be visible to us, and objects outside of the scene will be clipped off. This is to remove unnecessary operations.
The visual body of an orthographic projection camera is a cuboid, and the Orthographiccamera constructor is this: Orthographiccamera (left, right, top, bottom, near, far)
The camera itself can be viewed as a point, and left indicates the distance from the camera in both directions. Several other parameters are the same. The six parameters respectively define the position of the six faces of the scene body.
It can be approximated that objects in the scene are projected parallel to the near plane, and then the image on the near plane is rendered onto the screen.
Perspective projection Camera
The visual body of the perspective projection camera is a four-bevel, and its constructor is this: Perspectivecamera (FoV, Aspect, near, far)
The FOV corresponds to the angle of view in the diagram, the upper and lower sides of the angle. Aspect is the aspect ratio of the near plane. In addition to near plane distance, far plane distance, you can only determine the visual body.
The perspective projection camera is very much in line with what we normally see, so in most cases we use a perspective projection camera to show the 3D effect.
Objects
With a camera, what do you always want to watch? Add some objects to the scene.
There are many objects for display in three, they all inherit from Object3d class, here we mainly look at mesh and points two kinds.
Mesh
As we all know, in the world of computers, an arc is connected by a finite line segment made up of a finite number of points. When you have a lot of segments, it looks like a smooth arc.
The three-dimensional model in a computer is similar, and the common practice is to describe it in a grid of triangles, which we call the mesh model.
This is the famous Stanford Rabbit. Its position in 3D graphics is similar to the famous Lena in the field of digital image processing.
Look at this rabbit, its surface is getting smoother/more accurate as the number of triangles increases.
In three, the mesh constructor is like this: mesh (geometry, material)
Geometry is its shape, and material is its material.
More than just mesh, these two properties are used to create many objects. Let's take a look at these two important attributes.
Geometry
Geometry, shape, quite intuitive. Geometry the purpose of describing an object's shape by storing the point set used in the model and the relationship between points (which points form a triangle).
Three provides a cube (actually a box), a plane (actually a rectangle), a sphere, a circle, a cylinder, a round table and many other basic shapes;
You can also construct the shape by defining the location of each point;
For more complex shapes, we can also import from external model files.
Material
Material, material, which is not as intuitive as the shape.
The material is actually a collection of all the visual properties of the object's surface except the shape, such as color, texture, smoothness, transparency, reflectivity, refractive index, and luminosity.
Here's a look at the relationship of material (Material), map (map), and texture (Texture).
The material above has been mentioned, it includes stickers and others.
Stickers are actually ' stickers ' and ' graphs ', which include where pictures and pictures should be posted.
The texture is actually ' picture '.
Three offers a variety of materials to choose from, allowing you to freely select materials such as diffuse reflection/specular reflection.
Points
Having finished the mesh, let's take a look at another object--points.
Points is actually a collection of points, which was previously known as particlesystem (particle system) for a long time, and was renamed points when the R68 version was renamed to POINTCLOUD,R72 version. The renaming is mainly because, mr.doob, the particle system should be a complete set of systems that includes the processing of particles and related physical properties, while the points in three is much simpler. So eventually this class is named points.
The typical effect points can achieve is this: the official example
Light
God said, "There is light!"
The light and shadow effect is the important factor to enrich the picture.
Three provides a variety of light sources including ambient light ambientlight, point Light pointlight, Spotlight spotlight, directional light directionallight, and hemispherical light hemispherelight.
Just add the required light to the scene.
Renderer
Creating objects in the scene, as well as light, and a camera for observing objects, is the time to render the things you see on the screen. This is what the render does.
Renderer binds a canvas object and can set properties such as size, default background color, and so on.
By invoking renderer's render function and passing in scene and camera, you can render the image to the canvas.
Let the screen move.
Now, a static picture can be obtained, how can we make it move?
Very simple idea, change the position of object in the scene AH angle ah various properties, and then re-call the render function rendering just fine.
So how is the timing of the re-rendering OK?
HTML5 provides us with Requestanimframe, which automatically calls incoming functions before each page redraw.
If we start with this rendering:
render(){ renderer.rendercamera);}
Just change to this:
render(){ requestAnimationFrame(render); 1; renderer.rendercamera);}
The object can be moved!
Give me a chestnut.
Let's use a simple example to comb the process.
First, write a page with a canvas element.
<! 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: %; height: %; } </style></head><body> <canvas id="Three_canvas"></Canvas></body></html>
Let's do the JavaScript section below.
Initialize firstRenderer
function initRenderer() { width = document.getElementById(‘three_canvas‘).clientWidth; height = document.getElementById(‘three_canvas‘).clientHeight; new THREE.WebGLRenderer({ //将Canvas绑定到renderer canvas: document.getElementById(‘three_canvas‘) }); renderer.setSize(width, height);//将渲染的大小设为与Canvas相同 renderer.setClearColor(0xFFFFFF1.0);//设置默认颜色与透明度}
Initialize the scene:
function initScene() { new THREE.Scene();}
To initialize the camera:
function initcamera() { //Simple orthographic projection camera, facing the center of the viewport, with the same viewport size as the canvas. Camera =NewThree. Orthographiccamera (Width/-2, Width/2, Height/2, Height/-2,1, +);//Set the camera's positionCamera.position.x =0; CAMERA.POSITION.Y =0; Camera.position.z = $;//Set the camera to the topcamera.up.x =0; CAMERA.UP.Y =1; Camera.up.z =0;//Set camera focus position (in fact, to determine a direction)Camera.lookat ({x:0Y:0Z:0});}
To uniquely determine the position and orientation of a camera, the position, up, and LookAt three properties are integral.
Here we create an orthographic projection camera, where I keep the view body size consistent with the screen resolution just for convenience, so that one unit length in the coordinate system corresponds to one pixel of the screen.
We put the camera on the z axis, facing the coordinates origin, the camera's upper direction for the Y axis, note that the direction of up and the direction of the LookAt is bound to be perpendicular (the analogy of their own head to know).
Add a cube below to the scene:
function initObject() { //创建一个边长为100的立方体 varnew THREE.CubeGeometry(100100100); newnew THREE.MeshNormalMaterial()); scene.add(object);}
Note that we used the normal material meshnormalmaterial, so that the color of each face of the cube is related to the direction of the face, making it easier to observe/debug.
In this simple demo I'm not going to add light and shade, and the normal material doesn't react to light.
Finally, create an animation loop.
function render() { requestAnimationFrame(render); 0.05; 0.05; renderer.render(scene, camera);}
Each redraw makes the cube spin a little bit.
When the page loads well, it's good to call the previous functions.
function threeStart() { initRenderer(); initCamera(); initScene(); initObject(); render();}window.onload = threeStart();
The complete demo is 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: %; height: %; } </style></head><body><canvas id="Three_canvas"></Canvas><script> varRenderer, camera, scene, light, object;varwidth, height; function initrenderer() {width = document.getElementById (' Three_canvas '). clientwidth; Height = document.getElementById (' Three_canvas '). clientheight; Renderer =NewThree. Webglrenderer ({canvas:document.getElementById (' Three_canvas ') }); Renderer.setsize (width, height); Renderer.setclearcolor (0xFFFFFF,1.0); } function initcamera() {Camera =NewThree. Orthographiccamera (Width/-2, Width/2, Height/2, Height/-2,1, +); Camera.position.x =0; CAMERA.POSITION.Y =0; Camera.position.z = $; camera.up.x =0; CAMERA.UP.Y =1; Camera.up.z =0; Camera.lookat ({x:0Y:0Z:0}); } function initscene() {Scene =NewThree. Scene (); } function initobject() { varGeometry =NewThree. Cubegeometry ( -, -, -); Object =NewThree. Mesh (Geometry,NewThree. 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, a rotating cube is displayed in the center of the screen.
Summary
The introduction to Three.js is here, and this article is basically a reference to the important components of three. In fact, there are a lot of things to summarize, but it may seem cumbersome to write in this article, the original intention is to want readers to read after the Three.js have an intuitive understanding of the general, do not intend to involve too much detail.
Good luck ~
Three.js Quick Start