Home Web Front-end JS Tutorial THREE.JS introductory tutorial (1) Understand before using THREE.JS_Basic knowledge

THREE.JS introductory tutorial (1) Understand before using THREE.JS_Basic knowledge

May 16, 2016 pm 05:43 PM

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:

Copy code The code is as follows:

// 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:
Copy code The code is as follows:

//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:
Copy the code The code is as follows:

// 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:
Copy the code The code is as follows:

// 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:
Copy the code The code is as follows:

// 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.
Copy code The code is as follows:

// 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:
Copy code The code is as follows:

// 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.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles