search
HomeWeb Front-endJS TutorialTHREE.JS introductory tutorial (1) Understand before using THREE.JS_Basic knowledge

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
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
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 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.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.