Home Web Front-end JS Tutorial Basic Introduction to Three.js JS Library

Basic Introduction to Three.js JS Library

Sep 15, 2017 am 09:15 AM
javascript getting Started

three.js is a webGL framework that is widely used due to its ease of use. Below, the editor of Script House will explain the basic configuration method of three.js through a case. Please refer to this article for details

Opening Statement

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 type the code and explore it 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 work

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

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

Start with an example!

First we build the html, as follows:


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>lesson1-by-shawn.xie</title>
 <!--引入Three.js-->
 <script src="Three.js"></script>
 <style type="text/css">
 p#canvas-frame{
  border: none;
  cursor: move;
  width: 1400px;
  height: 600px;
  background-color: #EEEEEE;
 }
 </style>
 </head>
 <body>
 <!--盛放canvas的容器-->
 <p id="container"></p>
 </body>
</html>
Copy after login

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) Specify the CSS style of "canvas3d" 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!

Let’s 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 the 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 a renderer object ( Attributes: The anti-aliasing effect is valid for settings);

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

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

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


//开启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)
}
Copy after login

2. Set up the camera camera

In OpenGL (WebGL), in the way objects in three-dimensional space are projected to two-dimensional space, there is perspective projection and orthographic projection cameras. 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 projection is widely used. In Three.js, you can also specify cameras in 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 the camera for perspective projection;

(2) Set the position coordinates of the camera;

(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 } );//设置视野的中心坐标
 }
Copy after login

3. Set the scene scene

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


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

4. Set the light source light

In the three-dimensional space of OpenGL (WebGL), there are two types of point light sources and spotlights. Furthermore, there is also a parallel light source (wireless high light source) as a special case of the point light source. In addition, as a parameter of the light source, settings such as [Ambient Light] can also be made. Correspondingly, [Point Light], [Spot Light], [Direction Light], and [Ambient Light] can be set in Three.js. Like OpenGL, multiple light sources can be set in a scene. Basically, it is a combination of ambient light and several other light sources. If you don't set ambient light, the surfaces not illuminated by light will become too dark. In this article, we first follow the steps below to set up the parallel light source, and then add ambient light.

(0) Declare global variables (objects)

(1) Set directional light source

(2) Set light source vector

(3) Add light source Go to the scene

Here we use the "DirectionalLight" class to declare an object called [light] to represent the directional light source


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

5. Set the object 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);
 }
Copy after login

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


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

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

总结

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

1.设置three.js渲染器

2.设置摄像机camera

3.设置场景scene

4.设置光源light

5.设置物体object

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

本例完整代码:


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>lesson1-by-shawn.xie</title>
 <!--引入Three.js-->
 <script src="Three.js"></script>
 <script type="text/javascript">
 //开启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 type="text/css">
 p#canvas3d{
  border: none;
  cursor: move;
  width: 1400px;
  height: 600px;
  background-color: #EEEEEE;
 }
 </style>
 </head>
 <body onload=&#39;threeStart();&#39;>
 <!--盛放canvas的容器-->
 <p id="canvas3d"></p>
 </body>
</html>
Copy after login

The above is the detailed content of Basic Introduction to Three.js JS Library. For more information, please follow other related articles on the PHP Chinese website!

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)

A Diffusion Model Tutorial Worth Your Time, from Purdue University A Diffusion Model Tutorial Worth Your Time, from Purdue University Apr 07, 2024 am 09:01 AM

Diffusion can not only imitate better, but also "create". The diffusion model (DiffusionModel) is an image generation model. Compared with the well-known algorithms such as GAN and VAE in the field of AI, the diffusion model takes a different approach. Its main idea is a process of first adding noise to the image and then gradually denoising it. How to denoise and restore the original image is the core part of the algorithm. The final algorithm is able to generate an image from a random noisy image. In recent years, the phenomenal growth of generative AI has enabled many exciting applications in text-to-image generation, video generation, and more. The basic principle behind these generative tools is the concept of diffusion, a special sampling mechanism that overcomes the limitations of previous methods.

Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Generate PPT with one click! Kimi: Let the 'PPT migrant workers' become popular first Aug 01, 2024 pm 03:28 PM

Kimi: In just one sentence, in just ten seconds, a PPT will be ready. PPT is so annoying! To hold a meeting, you need to have a PPT; to write a weekly report, you need to have a PPT; to make an investment, you need to show a PPT; even when you accuse someone of cheating, you have to send a PPT. College is more like studying a PPT major. You watch PPT in class and do PPT after class. Perhaps, when Dennis Austin invented PPT 37 years ago, he did not expect that one day PPT would become so widespread. Talking about our hard experience of making PPT brings tears to our eyes. "It took three months to make a PPT of more than 20 pages, and I revised it dozens of times. I felt like vomiting when I saw the PPT." "At my peak, I did five PPTs a day, and even my breathing was PPT." If you have an impromptu meeting, you should do it

All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award All CVPR 2024 awards announced! Nearly 10,000 people attended the conference offline, and a Chinese researcher from Google won the best paper award Jun 20, 2024 pm 05:43 PM

In the early morning of June 20th, Beijing time, CVPR2024, the top international computer vision conference held in Seattle, officially announced the best paper and other awards. This year, a total of 10 papers won awards, including 2 best papers and 2 best student papers. In addition, there were 2 best paper nominations and 4 best student paper nominations. The top conference in the field of computer vision (CV) is CVPR, which attracts a large number of research institutions and universities every year. According to statistics, a total of 11,532 papers were submitted this year, and 2,719 were accepted, with an acceptance rate of 23.6%. According to Georgia Institute of Technology’s statistical analysis of CVPR2024 data, from the perspective of research topics, the largest number of papers is image and video synthesis and generation (Imageandvideosyn

From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts From bare metal to a large model with 70 billion parameters, here is a tutorial and ready-to-use scripts Jul 24, 2024 pm 08:13 PM

We know that LLM is trained on large-scale computer clusters using massive data. This site has introduced many methods and technologies used to assist and improve the LLM training process. Today, what we want to share is an article that goes deep into the underlying technology and introduces how to turn a bunch of "bare metals" without even an operating system into a computer cluster for training LLM. This article comes from Imbue, an AI startup that strives to achieve general intelligence by understanding how machines think. Of course, turning a bunch of "bare metal" without an operating system into a computer cluster for training LLM is not an easy process, full of exploration and trial and error, but Imbue finally successfully trained an LLM with 70 billion parameters. and in the process accumulate

Five programming software for getting started with learning C language Five programming software for getting started with learning C language Feb 19, 2024 pm 04:51 PM

As a widely used programming language, C language is one of the basic languages ​​that must be learned for those who want to engage in computer programming. However, for beginners, learning a new programming language can be difficult, especially due to the lack of relevant learning tools and teaching materials. In this article, I will introduce five programming software to help beginners get started with C language and help you get started quickly. The first programming software was Code::Blocks. Code::Blocks is a free, open source integrated development environment (IDE) for

AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days AI in use | AI created a life vlog of a girl living alone, which received tens of thousands of likes in 3 days Aug 07, 2024 pm 10:53 PM

Editor of the Machine Power Report: Yang Wen The wave of artificial intelligence represented by large models and AIGC has been quietly changing the way we live and work, but most people still don’t know how to use it. Therefore, we have launched the "AI in Use" column to introduce in detail how to use AI through intuitive, interesting and concise artificial intelligence use cases and stimulate everyone's thinking. We also welcome readers to submit innovative, hands-on use cases. Video link: https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ Recently, the life vlog of a girl living alone became popular on Xiaohongshu. An illustration-style animation, coupled with a few healing words, can be easily picked up in just a few days.

A must-read for technical beginners: Analysis of the difficulty levels of C language and Python A must-read for technical beginners: Analysis of the difficulty levels of C language and Python Mar 22, 2024 am 10:21 AM

Title: A must-read for technical beginners: Difficulty analysis of C language and Python, requiring specific code examples In today's digital age, programming technology has become an increasingly important ability. Whether you want to work in fields such as software development, data analysis, artificial intelligence, or just learn programming out of interest, choosing a suitable programming language is the first step. Among many programming languages, C language and Python are two widely used programming languages, each with its own characteristics. This article will analyze the difficulty levels of C language and Python

Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Counting down the 12 pain points of RAG, NVIDIA senior architect teaches solutions Jul 11, 2024 pm 01:53 PM

Retrieval-augmented generation (RAG) is a technique that uses retrieval to boost language models. Specifically, before a language model generates an answer, it retrieves relevant information from an extensive document database and then uses this information to guide the generation process. This technology can greatly improve the accuracy and relevance of content, effectively alleviate the problem of hallucinations, increase the speed of knowledge update, and enhance the traceability of content generation. RAG is undoubtedly one of the most exciting areas of artificial intelligence research. For more details about RAG, please refer to the column article on this site "What are the new developments in RAG, which specializes in making up for the shortcomings of large models?" This review explains it clearly." But RAG is not perfect, and users often encounter some "pain points" when using it. Recently, NVIDIA’s advanced generative AI solution

See all articles