Three.js is a great open source WebGL library. WebGL allows JavaScript to operate the GPU and achieve true 3D on the browser side. However, this technology is still in the development stage, and the information is extremely scarce. Enthusiasts basically have to learn through the Demo source code and the source code of Three.js itself.
The foreign website aerotwist.com has six relatively simple introductory tutorials. I tried to translate them and share them with you.
I have used Three.js in some experimental projects, and I found it really helpful to quickly get started with browser 3D programming. With Three.js, you can not only create cameras, objects, lights, materials, etc., but you can also choose shaders and decide which technology (WebGL, Canvas or SVG) to use to render your 3D graphics on the web page. Three.js is open source, and you can even participate in the project. But for now, I'm going to focus on the basics and I'm going to show you how to use this engine.
As wonderful as Three.js is, it can also be maddening at times. For example, you will spend a lot of time reading the examples, doing some reverse engineering (in my case) to determine what a certain function does, and sometimes asking questions on GitHub. If you need to ask questions, Mr. doob and AlteredQualia are excellent choices.
1. Basics
I assume that you have passing knowledge of 3D graphics and have mastered JavaScript to a certain extent. If this is not the case, then learn a little bit first, otherwise you may be confused if you read this tutorial directly.
In our three-dimensional world, we have the following things. I'll take you step by step to create them.
1. Scene
2. Renderer
3. Camera
4. Object (with material)
Of course, you can also create other things, I hope you Do so.
2. Browser support
Let’s simply take a look at the browser support. Google's Chrome browser supports Three.js. In my experiments, Chrome is the best in terms of support for the renderer and the speed of the JavaScript interpreter: it supports Canvas, WebGL and SVG. And it runs very fast. The FireFox browser ranks second. Its JavaScript engine is half a beat slower than Chrome, but its support for renderers is also great, and the speed of FireFox is getting faster and faster with version updates. The Opera browser is gradually adding support for WebGL, and the Safari browser on Mac has an option to turn on WebGL. In general, these two browsers only support Canvas rendering. Microsoft's IE9 currently only supports Canvas rendering, and Microsoft seems not willing to support the new feature of WebGL, so we will definitely not use IE9 for experiments now.
3. Set up the scene
Assume that you have chosen a browser that supports all rendering technologies, and that you are going to render the scene via Canvas or WebGL (which is the more standardized choice). Canvas has broader support than WebGL, but WebGL can operate directly on the GPU, which means your CPU can focus on non-rendering work, such as the physics engine or interacting with the user.
No matter which renderer you choose, there is one thing you must keep in mind: JavaScript code needs to be optimized. 3D rendering is not an easy task for browsers (it would be great to be able to do it now), so if your rendering is too slow, you need to know where the bottleneck in your code is and, if possible, improve it.
Having said all that, I think you have downloaded the Three.js source code and introduced it into your html document. So how do you start creating a scene? Like this:
// Set scene size
var WIDTH = 400,
HEIGHT = 300;
// Set some camera parameters
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
// Get elements in the DOM structure
// - Assume we use JQuery
var $container = $('#container');
// Create renderer, camera and Scene
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 scene
scene.add(camera);
// The initial position of the camera is the origin
// Pull the camera Come back some (Translator's Note: Only in this way can you see the origin)
camera.position.z = 300;
// Start the renderer
renderer.setSize(WIDTH, HEIGHT);
// Will The renderer is added to the DOM structure
$container.append(renderer.domElement);
Look, it’s easy!
4. Building the Mesh Surface Now we have a scene, a camera and a renderer (in my case, a WebGL renderer of course), but we actually What haven’t you painted yet? In fact, Three.js provides support for loading 3D files in certain standard formats, which is great if you are modeling in Blender, Maya, Cinema4D or other tools. For the sake of simplicity (after all, we are just getting started!) let's consider primitives first. Primitives are basic geometric surfaces, such as the most basic spheres, planes, cubes, and cylinders. These primitives can be easily created using Three.js:
//Set the sphere parameters (Translator's Note: The sphere is divided into a 16×16 grid. If the last two parameters are 4 and 2, an octahedron will be generated, please imagine)
var radius = 50,
segments = 16,
rings = 16;
// material covers geometry to generate mesh
var sphere = new THREE.Mesh(
new THREE.SphereGeometry(
radius,
segments,
rings),
sphereMaterial);
// Add mesh to the scene
scene.add(sphere);
Okay, But what about the material on the sphere? In the code we use a sphereMaterial variable, we haven't defined it yet. So let’s take a look at how to create a material first.
5. Materials Undoubtedly, this is the most useful part of Three.js. This part provides several very easy-to-use general material models:
1.Basic material: represents a material that does not take lighting into account. This can only be said for now.
2.Lambert material: (Translator's note: Lambert surface, isotropic reflection).
3.Phong material: (Translator's note: Phong surface, a shiny surface, a reflection between specular reflection and Lambertian reflection, describing the reflection in the real world).
In addition, there are some other types of materials. For the sake of simplicity, I leave it to you to explore by yourself. In fact, materials are really easy to use when using a WebGL-type renderer. Why? Because in native WebGL you have to write a shader for each rendering yourself, and the shader itself is a huge project: simply put, the shader is written using GLSL language (OpenGL shader language) and is used to operate the GPU. Procedurally, this means you have to mathematically simulate lighting, reflections, etc., which quickly becomes an extremely complex job. 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 shows that this is a very flexible setting.
Now, let’s cover the sphere with the Lambertian material:
// Create the material for the sphere surface
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});
It is worth pointing out that when creating a material, in addition to color, there are many other parameters that can be specified, such as smoothness and environment maps. You may need to search this wiki page to confirm which properties can be set on the material, or any object provided by the Three.js engine.
6. Light If you want to render the scene now, you will see a red circle. Although we covered the sphere with a Lambertian material, there is no light in the scene. So according to the default settings, Three.js will return to full ambient light, and the apparent color of the object is the color of the object surface. Let's add a simple point light:
// Create A point light source
var pointLight =
new THREE.PointLight(0xFFFFFF);
// Set the position of the point light source
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
//Add point light source to the scene
scene.add(pointLight);
7. Rendering loop Obviously, everything is set up regarding the renderer. Everything is ready, we just need to:
// Draw !
renderer.render(scene, camera);
You're likely to render multiple times rather than just once, so if you're going to do a loop, you should use requestAnimationFrame. This is currently the best way to handle animations in the browser, and although it's not yet fully supported, I highly recommend you check out Paul Irish's blog.
8. Common object properties If you take a moment to browse the source code of Three.js, you will find that many objects inherit from Object3D. This base class contains many useful properties, such as position, rotation, and scaling information. In particular, our sphere is a Mesh object, and the Mesh object inherits from the Object3D object, but adds some of its own properties: geometry and material. Why do you say this? Because you will not be satisfied with just a ball on the screen that does nothing, and these (Translator's Note: in the base class) properties allow you to manipulate the lower-level details of the Mesh object and various materials.
// sphere is a mesh object
sphere. geometry
// sphere contains some point and surface information
sphere.geometry.vertices // an array
sphere.geometry.faces // another array
// mesh object inherits from object3d Object
sphere.position // Contains x, y, z
sphere.rotation // Same as above
sphere.scale // ... Same as above
9. The nasty secret I hope you'll figure it out quickly: if you modify, say, a mesh object's vertices attributes, you'll find that nothing changes during the render loop. Why? Because Three.js caches the information of the mesh object into a certain optimized structure. What you really need to do is give Three.js a flag telling it that if something changes, it needs to recalculate the structure in the cache:
// Set geometry to be dynamic, which allows the vertices to be changed
sphere.geometry.dynamic = true;
// Tell Three .js, the vertices need to be recalculated
sphere.geometry.__dirtyVertices = true;
// Tell Three.js, the vertices need to be recalculated
sphere.geometry.__dirtyNormals = true;
There are many more logos, but I find these two the most useful. You should only identify those properties that really need to be calculated in real time to avoid unnecessary computational overhead.
10. Summary I hope this brief introduction will be helpful to you. There’s nothing like rolling up your sleeves and getting your hands dirty, and I highly recommend you do so. Running 3D programs in the browser is fun, and using an engine like Three.js takes away a lot of the hassle, allowing you to focus on the really cool stuff in the first place.
I have packaged the source code of this tutorial, you can
download it as a reference.