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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools