THREE. JS getting started tutorial (1) THREE. JS before use

Source: Internet
Author: User

Three. js is a great open-source WebGL library. WebGL allows JavaScript to operate on GPUs and implement 3D in the browser. However, this technology is still in its development stage, and there is a shortage of materials. Fans should learn it through the Demo source code and the source code of Three. js.

Aerotwist.com has six simple tutorials. I try to translate them and share them with you.
I used Three. js in some experimental projects, and I found it really helpful for getting started with browser 3D programming quickly. Through Three. js, you can not only create cameras, objects, light, materials, etc., you can also choose a coloring tool, you can decide which technology (WebGL, Canvas or SVG) to use) render your 3D images on the web page. Three. js is open-source and you can even participate in this project. But now I will focus on the basic introduction, and I will show you how to use this engine.

Three. js is so amazing, but sometimes it is crazy. For example, you will spend a lot of time reading routines, doing some reverse engineering (in my case) to determine the role of a function, and sometimes go to GitHub to ask questions. If you need to ask questions, Mr. doob and AlteredQualia are excellent choices.

1. Basics
I assume that your 3D graphics knowledge passes through and you have mastered JavaScript to some extent. If this is not the case, you should first learn something. Otherwise, you may be confused if you read this tutorial directly.

In our 3D world, we have the following things. I will show you how to create them step by step.
1. Scenario
2. Renderer
3. Camera
4. Objects (with materials)
Of course, you can also create something else, and I hope you will do the same.
2. browser support
Let's take a brief look at the browser support. Google's Chrome browser supports Three. js. In my experiment, Chrome is the best in terms of support for Renderer and speed of JavaScript interpreters: it supports Canvas, WebGL, and SVG, and runs very fast. The FireFox browser ranks second. Its JavaScript Engine is half slower than Chrome, but it also has great support for the Renderer, and FireFox is faster and faster with version updates. Operabrowser is gradually adding support for WebGL. Safari on Mac has an option to enable WebGL. In general, the two browsers only support Canvas rendering. Microsoft's IE9 currently only supports Canvas rendering, and Microsoft does not seem to be willing to support the new WebGL feature. Therefore, we certainly will not use IE9 for experiments.
3. Set the scenario
Suppose you have selected a browser that supports all rendering technologies, and you are ready to render the scenario through Canvas or WebGL (this is a more standardized choice ). Canvas is more widely supported than WebGL, but WebGL can be operated directly on the GPU, which means that your CPU can focus on non-rendering work, for example, a physical engine or user interaction.

Whatever Renderer you choose, you must keep in mind that JavaScript code needs to be optimized. 3D display is not an easy task for browsers (it is great to do so now), so if your rendering is too slow, you need to know where the bottleneck of your code is, if possible, improve it.

After that, I think you have downloaded the source code of Three. js and introduced it into your html document. How can we create a scenario? Like this:
Copy codeThe Code is as follows:
// Set the scenario size
Var WIDTH = 400,
HEIGHT = 300;
// Set some camera parameters
Var VIEW_ANGLE = 45,
ASPECT = WIDTH/HEIGHT,
NEAR = 0.1,
FAR = 10000;
// Obtain the elements in the DOM Structure
//-Assume that we use JQuery
Var $ container = $ ('# iner ');
// Create a Renderer, camera, and scenario
Var renderer = new THREE. WebGLRenderer ();
Var camera =
New THREE. PerspectiveCamera (
VIEW_ANGLE,
ASPECT,
NEAR,
FAR );
Var scene = new THREE. Scene ();
// Add the camera to the scenario
Scene. add (camera );
// The initial position of the camera is the origin
// Pull the camera back (note: in this way, you can see the origin)
Camera. position. z= 300;
// Start the Renderer
Renderer. setSize (WIDTH, HEIGHT );
// Add the Renderer to the DOM Structure
$ Container. append (renderer. domElement );

Look, it's easy!
4. Build a grid surface
Now we have a scenario, a camera and a Renderer (in my example, of course, a WebGL Renderer), but we haven't actually painted anything yet. In fact, Three. js provides support for loading 3D files in several standard formats. If you create a model in Blender, Maya, Cinema4D, or other tools, this is amazing. For simplicity (after all, this is just the beginning !) Let's first consider the primitive. A primitive is a basic geometric surface, such as the most basic sphere, plane, cube, and cylinder. Using Three. js, you can easily create these elements:
Copy codeThe Code is as follows:
// Set the Sphere Parameters (note: the sphere is divided into 16 × 16 grids. If the last two parameters are 4 or 2, an octal surface is generated. Imagine)
Var radius = 50,
Segments = 16,
Rings = 16;
// The material overwrites the geometry to generate a mesh.
Var sphere = new THREE. Mesh (
New THREE. SphereGeometry (
Radius,
Segments,
Rings ),
SphereMaterial );
// Add the mesh to the scene
Scene. add (sphere );

Okay, but what about the materials on the Sphere? In the code, we use a sphereMaterial variable. We haven't defined it yet. Let's take a look at how to create materials.
5. Material
Undoubtedly, this is the most useful part of Three. js. This section provides several easy-to-use general material models:
1. Basic Material: indicates a material that does not take light into account. Now we can only say this.
2. Lambert material: (Translator's note: Lamber plane, Al reflection ).
3. Phong material: (Translator's note: Feng's surface, shiny surface, between the reflection between the mirror reflection and the Longman reflection, describes the reflection of the real world ).

In addition, there are some other types of materials that you can explore for simplicity. In fact, when using a WebGL Renderer, the material is really easy to use. Why? Because in native WebGL, you must write a shader for each rendering, and the parser itself is a huge project: in short, the shader is written in the GLSL language (OpenGL language) and used to operate GPU programs. This means that you need to simulate illumination, reflection, and so on in mathematics, this soon became a very complex task. Thanks to Three. js, you don't have to write your own shader. Of course, if you want to write it yourself, you can use MeshShaderMaterial, which is flexible.

Now, let's cover the sphere with the longer surface material:
Copy codeThe Code is as follows:
// Create a sphere surface material
Var sphereMaterial =
New THREE. MeshLambertMaterial (
{
Color: 0xCC0000
});

It is worth noting that there are many other parameters in addition to color when creating materials, such as smoothness and environment textures. You can retrieve this Wiki page to confirm which attributes can be set on the material or any objects provided by the Three. js engine.
6. Light
If you want to render the scene now, you will see a red circle. Although we have covered the Lamber surface material on the sphere, there is no light in the scene. Therefore, according to the default setting, Three. js will return to the full ambient light, and the color of the object looks like the color of the object surface. Let's add a simple point light source:
Copy codeThe Code is as follows:
// Create a light source
Var pointLight =
New THREE. PointLight (0 xFFFFFF );
// Set the position of the Point Light Source
PointLight. position. x = 10;
PointLight. position. y = 50;
PointLight. Location. z = 130;
// Add the point light source to the scenario
Scene. add (pointLight );

7. Rendering cycle
Obviously, everything about the Renderer is set. Everything is ready. Now we only need:
Copy codeThe Code is as follows:
// Draw!
Renderer. render (scene, camera );

You are likely to render it multiple times rather than just one time, so if you want to make a loop, you should use requestAnimationFrame. This is currently the best way to process animations in a browser. Although it is not yet fully supported, I strongly recommend that you read Paul Irish's blog.
8. Common Object Attributes
If you spend some time browsing the source code of Three. js, you will find that many objects are inherited from Object3D. This base class contains many useful attributes, such as location, rotation, and scaling information. In particular, our sphere is a Mesh object, and the Mesh object inherits from the Object3D object, but adds its own attributes: geometry and material. Why? Because you will not be satisfied with a ball that does nothing on the screen) attribute allows you to operate more underlying details and various materials of Mesh objects.
Copy codeThe Code is as follows:
// Sphere is a mesh object.
Sphere. geometry
// Sphere contains some vertex and surface information
Sphere. geometry. vertices // an array
Sphere. geometry. faces // another Array
// The mesh object inherits from the object3d object.
Sphere. position // contains x, y, z
Sphere. rotation // same as above
Sphere. scale //... same as above

9. Nasty secrets
I hope that you can quickly understand that if you modify the vertex attribute vertices of a mesh object, for example, you will find that nothing has changed in the rendering loop. Why? Because Three. js caches the mesh object information into an optimized structure. What you really want to do is to give Three. js an identifier to tell it that if something has changed, you need to re-calculate the structure in the cache:
Copy codeThe Code is as follows:
// Set geometry to dynamic so that the vertex can be changed.
Sphere. geometry. dynamic = true;
// Tell Three. js that the vertex needs to be re-computed
Sphere. geometry. _ dirtyVertices = true;
// Tell Three. js that the vertex needs to be re-computed
Sphere. geometry. _ dirtyNormals = true;

There are more identifiers, but I find these two are the most useful. You should only identify the attributes that actually require real-time computing to avoid unnecessary computing overhead.
10. Summary
I hope this brief introduction will help you. Nothing is better than rolling up your sleeves. I strongly suggest you do this. It is interesting to run 3D programs in a browser, and using an engine like Three. js frees you from a lot of trouble, allowing you to focus on the real cool stuff from the beginning.

I have packaged the source code of this tutorial. You can download it as a reference.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.