Home > Web Front-end > JS Tutorial > body text

Detailed explanation of Three.js usage

php中世界最好的语言
Release: 2018-04-17 10:52:34
Original
4368 people have browsed it

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:

<!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) 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)
}
Copy after login

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

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();
 }
Copy after login

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);// 追加光源到场景
 }
Copy after login

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);
 }
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('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)
 }
 //设置相机
 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

相信看了本文案例你已经掌握了方法,更多精彩请关注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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!