search
HomeWeb Front-endJS TutorialThree.js basic introductory learning tutorial

Three.js basic introductory learning tutorial

Jan 18, 2018 pm 02:22 PM
javascriptStudy tutorial

This article mainly introduces the Three.js basic learning tutorial in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

1. Three.js official website and three necessary conditions for using Three.js

1.Three.js official website https://threejs.org/

2. Three necessary conditions for using Three.js

(To actually be able to display anything with Three.js, we need three things: A scene, a camera, and a renderer so we can render the scene with the camera.)

roughly means that anything displayed can be achieved using three.js, and three conditions must be met: a scene, a camera, a renderer. All three are indispensable.

2. The relationship between the three necessary conditions for using Three.js (a scene scene, a camera camera, a renderer renderer) 


As shown in the picture above, to illustrate the relationship between a scene, a camera, and a renderer renderer[/code]

1.Scene scene is a container of objects [popularly understood as holding things]. Developers can put the required characters into the scene, such as apples and grapes. At the same time, the character itself also manages its position in the scene.

2.The function of camera camera is to face the scene, pick a suitable scene in the scene, and take a photo of it. [You can imagine the eyes of an adult]

3.The function of renderer is to put the pictures taken by the camera into the browser to display

3. Use the above theory to practice the official website case

The rendering is as follows

##Official website case implementation source code


<html>
 <head>
 <title>My first three.js app</title>
 <style>
  body { margin: 0; }
  canvas { width: 100%; height: 100% }
 </style>
 </head>
 <body>
 <script src="./lib/three.js"></script>
 <script>
  //创建一个场景对象
  var scene = new THREE.Scene();
  //创建一个相机对象
  var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
  
  //创建一个渲染器对象
  var renderer = new THREE.WebGLRenderer(); 
  //设置画布尺寸
  renderer.setSize( window.innerWidth, window.innerHeight );
  //设置画布色
   renderer.setClearColor(0x00AABB, 1.0);
   //将渲染画布添加到浏览器中,以便后面剩放相机拍下的景
  document.body.appendChild( renderer.domElement );
  
  //创建一个几何体长、宽、高分别为1几何体对象
  var geometry = new THREE.BoxGeometry( 1, 1, 1 );
  //材料、皮肤
  var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  //将material材料添加到几何体geometry,产生新的对象几何体cube
  var cube = new THREE.Mesh( geometry, material );
  //将几何体添加至场景中
  scene.add( cube );
  //设置相机z轴,垂直电脑屏幕位置
  camera.position.z = 5;
   
  var render = function () {
  /*requestAnimationFrame( render ); //循环渲染
  cube.rotation.x += 0.1; //x轴每秒旋转60次
  cube.rotation.y += 0.1;//y轴每秒旋转60次*/
  renderer.render(scene, camera); //实时将相机拍下的几何体渲染到场景中
  };
  render();
</script>
 </body>
</html>

It is not difficult to find from the official website case that the default observation direction of the camera is the direction of the screen (negative z-axis direction). When the coordinates are changed, the camera must be pointed to the origin to observe the object

Negative direction of z-axis? ? ? Therefore, it is necessary to talk about the three-dimensional coordinates here (as shown below)

The camera points to the origin? ? ? Let’s talk about the camera camera (very important!! Imagine what it feels like when people can’t see things).

In the case, a perspective camera is used (objects that are closer from the viewpoint are larger, and objects that are far away are drawn A smaller way, consistent with the way we see objects in daily life)

##var camera = new THREE.PerspectiveCamera(fov, aspect, near,far)

new THREE.PerspectiveCamera(fov, aspect, near,far) Perspective camera

Viewing angle: fov Here viewing angle (some places (called shooting distance)), the smaller the objects in the scene, the smaller the field of view angle, the larger the objects in the scene
Aspect ratio: aspect
The closest distance between the camera and the viewing volume: near
The camera is away from the viewing volume The farthest distance of the volume: far

In summary, I believe that it should be very simple to understand the camera based on the above three-dimensional coordinates and camera diagram. Next, modify the above case (explain the mouse scrolling to zoom in and out in the following case) , three-dimensional rotation are all based on the camera)

Four. Modify the official website plan and set the camera orientation and camera position

Use the [lookAt] method to set the camera center of vision. The parameter of "lookAt()" is an object whose attributes include center coordinates "x", "y" and "z".


Set the upward direction of the camera to the positive y-axis camera.up.x = 0; camera.up.y = 1/*Camera orientation--The upper direction of the camera is the y-axis*/; camera. up.z = 0;


5. Implementation of rotating cube

Rotation animation principle The camera rotates around the y-axis and continuously modifies the camera's x and z-axis positions. And keep the objects in the scene in the camera's field of view, put the pictures taken by the camera in real time and display them in the browser

##
//相机围绕y轴旋转,不断修改相机x、z轴位置,并且保持场景中的物体一直再相机的视野中
//实时渲染成像
function animation(){
  var timer = Date.now()*0.0001;
  camera.position.x = Math.cos(timer)*100;
  camera.position.z = Math.sin(timer)*100;
  camera.lookAt(scene.position); //设置相机视野中心
  renderer.render(scene, camera);
  requestAnimationFrame(animation);//渲染回调函数
}

The effect diagram is as follows

Rotating Cube - Case Source Code

<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>旋转立方体 </title>
 <style>
  #canvas-frame {
  width: 100%;
  height: 600px;
  }
 </style>
 </head>
 <body onload="threeStart()">
 <p id="canvas-frame" ></p>
 </body>
 <script type="text/javascript" src="./lib/three.js" ></script>
 <script type="text/javascript">
  var renderer, //渲染器
  width = document.getElementById(&#39;canvas-frame&#39;).clientWidth, //画布宽
  height = document.getElementById(&#39;canvas-frame&#39;).clientHeight; //画布高
  //初始化渲染器
  function initThree(){
  renderer = new THREE.WebGLRenderer({
   antialias : true
   //canvas: document.getElementById(&#39;canvas-frame&#39;)
  });
  renderer.setSize(width, height);
  renderer.setClearColor(0xFFFFFF, 1.0);
  document.getElementById(&#39;canvas-frame&#39;).appendChild(renderer.domElement);
  renderer.setClearColor(0xFFFFFF, 1.0);
  }
  //初始化场景
  var scene;
  function initScene(){
  scene = new THREE.Scene();
  }
  var camera;
  function initCamera() { //透视相机
  camera = new THREE.PerspectiveCamera(45, width/height , 1, 10000);
  camera.position.x = 50;
  camera.position.y = 150;
  camera.position.z =150;
  camera.up.x = 0;
  camera.up.y = 1; //相机朝向--相机上方为y轴
  camera.up.z = 0;
  camera.lookAt({ //相机的中心点
   x : 0,
   y : 0,
   z : 0
  });
   
  // camera 正交相机
  /*camera = new THREE.OrthographicCamera(-300, 300, 100, -100, 1, 10000);
  camera.position.x = 250;
  camera.position.y = 100;
  camera.position.z = 1800;
  camera.up.x = 0;
  camera.up.y = 1; //相机朝向--相机上方为y轴
  camera.up.z = 0;
  camera.lookAt({ //相机的中心点
   x : 0,
   y : 0,
   z : 0
  });*/
  }
  
  function initLight(){
  // light--这里使用环境光
  //var light = new THREE.DirectionalLight(0xffffff); /*方向性光源*/
  //light.position.set(600, 1000, 800);
  var light = new THREE.AmbientLight(0xffffff); //模拟漫反射光源
  light.position.set(600, 1000, 800); //使用Ambient Light时可以忽略方向和角度,只考虑光源的位置
  scene.add(light);
  }
  function initObject(){ //初始化对象
   
  //初始化地板
  initFloor();
  }
  function initGrid(){ //辅助网格
  var helper = new THREE.GridHelper( 1000, 50 );
  helper.setColors( 0x0000ff, 0x808080 );
  scene.add( helper );
  }
  
  function initFloor(){
  //创建一个立方体
  var geometry = new THREE.BoxGeometry(80, 20, 80);
   for ( var i = 0; i < geometry.faces.length; i += 2 ) {
   var hex = Math.random() * 0xffffff;
   geometry.faces[ i ].color.setHex( hex );
   geometry.faces[ i + 1 ].color.setHex( hex );
  }
  var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors} );
  //将material材料添加到几何体geometry
  var mesh = new THREE.Mesh(geometry, material);
  mesh.position = new THREE.Vector3(0,0,0);
  scene.add(mesh);
  }
 
  
  //初始化页面加载
  function threeStart(){
  //初始化渲染器
  initThree();
  //初始化场景
  initScene();
  //初始透视化相机
  initCamera();
  //初始化光源
  //initLight();
  //模型对象
  initObject();
  //初始化网格辅助线
  initGrid();
  //renderer.render(scene, camera);
  //实时动画
  animation();
  
  }
  /*
  * 旋转原理
  * 相机围绕y轴旋转
  * 不断修改相机x、z轴位置,并且保持场景中的物体一直再相机的视野中,
  * 实时将相机拍摄下来的图片,放到浏览器中去显示
  */
  function animation(){
  //渲染成像
  var timer = Date.now()*0.0001;
  camera.position.x = Math.cos(timer)*100; //相机位置x轴方向
  camera.position.z = Math.sin(timer)*100; //相机位置y轴方向
  //设置相机视野中心
  camera.lookAt(scene.position);
  //渲染成像
  renderer.render(scene, camera);
  //渲染回调animation函数
  requestAnimationFrame(animation);
  }
 </script>
</html>

This is complete, attached is a personal drawing flowchart

related suggestion:

JS library Three.js basic introduction

Three.js basic part learning

How to run three.js locally Detailed explanation

Three.js implements 3D model display

Three.js entry hello world and how to draw lines

The above is the detailed content of Three.js basic introductory learning tutorial. 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

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