search
HomeWeb Front-endJS TutorialDetailed explanation of Three.js usage

This time I will bring you a detailed explanation of the use of Three.js, what are the precautions when using Three.js, the following is a practical case, let's take a look.

Opening remarks

webGL allows us to achieve 3D effects on canvas. Three.js is a webGL framework that is widely used due to its ease of use. If you want to learn webGL, it is a good choice to abandon those complicated native interfaces and start with this framework.

The blogger is also currently learning three.js and found that the relevant information is very scarce, and even the official API documentation is very rough. Many effects require you to slowly code and explore by yourself. So the purpose of writing this tutorial is to summarize it myself, and to share it with everyone.

This article is the first in a series of tutorials: Getting Started. In this article, I will take a simple demo as an example to explain the basic configuration method of three.js. After studying this article, you will learn how to draw a three-dimensional graphic in the browser!

Preparation

Before writing code, you must first download the latest three.js framework package and introduce three.js into your page. Of course, there are also many demos in the package for everyone to learn;

Chrome is currently the best browser that supports webGL, followed by Firefow. Domestic Aoyou and Cheetah can also run after testing.

Get started with examples!

First we build html, as follows:

nbsp;html>

 
 <meta>
 <title>lesson1-by-shawn.xie</title>
 <!--引入Three.js-->
 <script></script>
 <style>
 p#canvas-frame{
  border: none;
  cursor: move;
  width: 1400px;
  height: 600px;
  background-color: #EEEEEE;
 }
 </style>
 
 
 <!--盛放canvas的容器-->
 <p></p>
 

Prepare an area consistent with the size of the canvas frame for WebGL drawing. Specifically:

(1) Add the p element with the id "canvas3d" to the body tag.

(2) The CSS style of "canvas3d" is specified in the style tag.

It should be noted that we do not need to write a tag, we only need to define the p that holds the canvas. The canvas is dynamically generated by three.js!

Next we start writing the script. We will build a simple three-dimensional model through the following five steps, which are also the basic steps of three.js:

1. Set up three.js renderer

The process of mapping objects in three-dimensional space to a two-dimensional plane is called three-dimensional rendering. Generally speaking, we call the software that performs rendering operations a renderer. Specifically, the following processing is required.

(0) Declare global variables (objects);

(1) Get the height and width of the canvas "canvas-frame";

(2) Generate renderer object (property: anti-aliasing effect is set to valid);

(3) Specify the height and width of the renderer (the same size as the canvas frame);

(4) Append the [canvas] element to the [canvas3d] element;

(5) Set the clear color (clearColor) of the renderer.

//开启Three.js渲染器
var renderer;//声明全局变量(对象)
function initThree() {
 width = document.getElementById('canvas3d').clientWidth;//获取画布「canvas3d」的宽
 height = document.getElementById('canvas3d').clientHeight;//获取画布「canvas3d」的高
 renderer=new THREE.WebGLRenderer({antialias:true});//生成渲染器对象(属性:抗锯齿效果为设置有效)
 renderer.setSize(width, height );//指定渲染器的高宽(和画布框大小一致)
 document.getElementById('canvas3d').appendChild(renderer.domElement);//追加 【canvas】 元素到 【canvas3d】 元素中。
 renderer.setClearColorHex(0xFFFFFF, 1.0);//设置canvas背景色(clearColor)
}

2.Set camera camera

In OpenGL (WebGL), there are two types of cameras, perspective projection and orthographic projection, in the way objects in three-dimensional space are projected into two-dimensional space. Perspective projection is a method in which objects closer to the viewpoint are larger and objects farther away are drawn smaller. This is consistent with the way we see objects in daily life. Orthographic projection is to draw objects in a uniform size regardless of the distance from the viewpoint. In fields such as architecture and design, objects need to be drawn from various angles, so this kind of projection is widely used. In Three.js It is also possible to specify cameras with both perspective projection and orthographic projection. This article follows the steps below to set up the perspective projection method.

(0) Declare global variables (objects);

(1) Set up the camera for perspective projection;

(2) Set the camera’s position coordinates;

(3) Set the top of the camera to the "z" axis direction;

(4) Set the center coordinates of the field of view.       

  //设置相机
 var camera;
 function initCamera() { 
 camera = new THREE.PerspectiveCamera( 45, width / height , 1 , 5000 );//设置透视投影的相机,默认情况下相机的上方向为Y轴,右方向为X轴,沿着Z轴朝里(视野角:fov 纵横比:aspect 相机离视体积最近的距离:near 相机离视体积最远的距离:far)
 camera.position.x = 0;//设置相机的位置坐标
 camera.position.y = 50;//设置相机的位置坐标
 camera.position.z = 100;//设置相机的位置坐标
 camera.up.x = 0;//设置相机的上为「x」轴方向
 camera.up.y = 1;//设置相机的上为「y」轴方向
 camera.up.z = 0;//设置相机的上为「z」轴方向
 camera.lookAt( {x:0, y:0, z:0 } );//设置视野的中心坐标
 }

3.Set scene

A scene is a three-dimensional space. Use the [Scene] class to declare an object called [scene]. ˆ ˆ ˆ ˆ

  //设置场景
 var scene;
 function initScene() { 
 scene = new THREE.Scene();
 }

4. Set the light source light

OpenGL(WebGL)的三维空间中,存在点光源和聚光灯两种类型。 而且,作为点光源的一种特例还存在平行光源(无线远光源)。另外,作为光源的参数还可以进行 [环境光] 等设置。 作为对应, Three.js中可以设置 [点光源(Point Light)] [聚光灯(Spot Light)] [平行光源(Direction Light)],和 [环境光(Ambient Light)]。 和OpenGL一样、在一个场景中可以设置多个光源。 基本上,都是环境光和其他几种光源进行组合。 如果不设置环境光,那么光线照射不到的面会变得过于黑暗。 本文中首先按照下面的步骤设置平行光源,在这之后还会追加环境光。

(0) 声明全局变量(对象)

(1) 设置平行光源

(2) 设置光源向量

(3) 追加光源到场景

这里我们用「DirectionalLight」类声明一个叫 [light] 的对象来代表平行光源

    //设置光源
 var light;
 function initLight() { 
 light = new THREE.DirectionalLight(0xff0000, 1.0, 0);//设置平行光源
 light.position.set( 200, 200, 200 );//设置光源向量
 scene.add(light);// 追加光源到场景
 }

5.设置物体object

   这里,我们声明一个球模型   

   //设置物体
 var sphere;
 function initObject(){ 
 sphere = new THREE.Mesh(
  new THREE.SphereGeometry(20,20), //width,height,depth
  new THREE.MeshLambertMaterial({color: 0xff0000}) //材质设定
 );
 scene.add(sphere);
 sphere.position.set(0,0,0);
 }

最后,我们写一个主函数执行以上五步:

        //执行
 function threeStart() {
 initThree();
 initCamera();
 initScene(); 
 initLight();
 initObject();
 renderer.clear(); 
 renderer.render(scene, camera);
 }

这时,测试以上程序,你会发现浏览器窗口中出现了你绘制的球形模型

总结

以上就是three.js的入门内容,我们核心的五步就是:

1.设置three.js渲染器

2.设置摄像机camera

3.设置场景scene

4.设置光源light

5.设置物体object

可能其中有些设置你还不太清楚,没关系,后面几篇文章会对以上五个主要步骤进行详细的讲解,敬请期待~~

本例完整代码:

nbsp;html>

 
 <meta>
 <title>lesson1-by-shawn.xie</title>
 <!--引入Three.js-->
 <script></script>
 <script>
 //开启Three.js渲染器
 var renderer;//声明全局变量(对象)
 function initThree() {
 width = document.getElementById(&#39;canvas3d&#39;).clientWidth;//获取画布「canvas3d」的宽
 height = document.getElementById(&#39;canvas3d&#39;).clientHeight;//获取画布「canvas3d」的高
 renderer=new THREE.WebGLRenderer({antialias:true});//生成渲染器对象(属性:抗锯齿效果为设置有效)
 renderer.setSize(width, height );//指定渲染器的高宽(和画布框大小一致)
 document.getElementById(&#39;canvas3d&#39;).appendChild(renderer.domElement);//追加 【canvas】 元素到 【canvas3d】 元素中。
 renderer.setClearColorHex(0xFFFFFF, 1.0);//设置canvas背景色(clearColor)
 }
 //设置相机
 var camera;
 function initCamera() { 
 camera = new THREE.PerspectiveCamera( 45, width / height , 1 , 5000 );//设置透视投影的相机,默认情况下相机的上方向为Y轴,右方向为X轴,沿着Z轴朝里(视野角:fov 纵横比:aspect 相机离视体积最近的距离:near 相机离视体积最远的距离:far)
 camera.position.x = 0;//设置相机的位置坐标
 camera.position.y = 50;//设置相机的位置坐标
 camera.position.z = 100;//设置相机的位置坐标
 camera.up.x = 0;//设置相机的上为「x」轴方向
 camera.up.y = 1;//设置相机的上为「y」轴方向
 camera.up.z = 0;//设置相机的上为「z」轴方向
 camera.lookAt( {x:0, y:0, z:0 } );//设置视野的中心坐标
 }
 //设置场景
 var scene;
 function initScene() { 
 scene = new THREE.Scene();
 }
 //设置光源
 var light;
 function initLight() { 
 light = new THREE.DirectionalLight(0xff0000, 1.0, 0);//设置平行光源
 light.position.set( 200, 200, 200 );//设置光源向量
 scene.add(light);// 追加光源到场景
 }
 //设置物体
 var sphere;
 function initObject(){ 
 sphere = new THREE.Mesh(
  new THREE.SphereGeometry(20,20), //width,height,depth
  new THREE.MeshLambertMaterial({color: 0xff0000}) //材质设定
 );
 scene.add(sphere);
 sphere.position.set(0,0,0);
 }
 //执行
 function threeStart() {
 initThree();
 initCamera();
 initScene(); 
 initLight();
 initObject();
 renderer.clear(); 
 renderer.render(scene, camera);
 }
 </script>
 <style>
 p#canvas3d{
  border: none;
  cursor: move;
  width: 1400px;
  height: 600px;
  background-color: #EEEEEE;
 }
 </style>
 
 
 <!--盛放canvas的容器-->
 <p></p>
 

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Angular js操作用户的方法

token怎么储存在客户端localStorage内

AngularJS购物车结算时全选反选z

The above is the detailed content of Detailed explanation of Three.js usage. For more information, please follow other related articles on the PHP Chinese website!

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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools