当前位置:网站首页>Use threejs simple Web3D effect
Use threejs simple Web3D effect
2022-07-01 08:08:00 【CK continues to grow】
Catalog
I saw one on the Internet a few days ago threejs Implementation of web 3d Animation , It's cool , So I made a special trip to find out threejs. Let's first look at the official use threejs To achieve the effect of :

1. threejs Introduce
threejs It's based on the original WebGL API And shader encapsulation 3D engine , That's one .js library . Directly through the original WebGL Write programs directly , It's a little bit of a hassle , therefore threejs That's right WebGL Made a layer of encapsulation , It's so convenient web Start developing web 3d Application .
therefore WebGL yes threejs The basis of , Simple projects don't usually use the bottom layer WebGL knowledge , But learning WebGl Helps to understand threejs, If you use Three.js When a development project needs custom shaders , Must also be to learn from the bottom WebGL And shaders GLSL knowledge .
2. thresjs Use
First, let's take a look at the example effect we have achieved , Realize a cylinder that can be operated by the mouse :

Code implementation :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script src="js/three.js"></script>
<script src="js/OrbitControls.js"></script>
<script>
/**
* Scene object creation
*/
const scene = new THREE.Scene();
/**
* Cube geometry objects Geometry
*/
const geometry = new THREE.BufferGeometry(); // Create a Buffer Type geometry object
// Type array to create vertex data
const vertices = new Float32Array([
0, 0, 0, // The vertices 1 coordinate
50, 0, 0, // The vertices 2 coordinate
0, 100, 0, // The vertices 3 coordinate
0, 0, 10, // The vertices 4 coordinate
0, 0, 100, // The vertices 5 coordinate
50, 0, 10, // The vertices 6 coordinate
]);
// Create an attribute buffer object
const attribue = new THREE.BufferAttribute(vertices, 3); //3 One for a group , Representing a vertex xyz coordinate
// Set up the geometry attributes The location of the property
geometry.attributes.position = attribue;
/**
* Material object
*/
const material = new THREE.MeshBasicMaterial({
color: 0x0000ff, // Triangle color
side: THREE.DoubleSide // You can see it on both sides
});
/**
* Mesh model objects Mesh, Construction through geometric objects and materials of geometric objects
*/
const cube = new THREE.Mesh(geometry, material);
scene.add( cube );
/**
* Auxiliary coordinate system Parameters 250 Represents the size of the coordinate system , It can be set according to the scene size
*/
var axisHelper = new THREE.AxesHelper(250);
scene.add(axisHelper);
/**
* Lighting settings
*/
// Point source 1
var point = new THREE.PointLight(0xffffff);
point.position.set(400, 200, 300); // Position of point light source
scene.add(point); // Add point lights to the scene
// Point source 2 Location and point About the origin symmetry
var point2 = new THREE.PointLight(0xffffff);
point2.position.set(-400, -200, -300); // Position of point light source
scene.add(point2); // Add point lights to the scene
// The ambient light
var ambient = new THREE.AmbientLight(0x444444);
scene.add(ambient);
/**
* Camera settings
* @type {PerspectiveCamera}
*/
var width = window.innerWidth; // Window width
var height = window.innerHeight; // Window height
var k = width / height; // Window aspect ratio
var s = 500; // Three dimensional scene display range control coefficient , The larger the coefficient , The larger the scope of the display
// Create camera objects
const camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
// const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.set(200, 300, 200); // Set camera position
camera.lookAt(scene.position); // Set camera orientation ( Point to the scene object )
// camera.position.z = 5;
/**
* Renderers
*/
/* WebGLRender */
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0xb9d3ff, 1); // Set the background color
document.body.appendChild( renderer.domElement );
/**
* Manual operation
* */
function render(){
renderer.render(scene,camera);
}
render()
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.addEventListener('change', render);// Monitor the mouse 、 Keyboard events
</script>
</body>
</html>Detailed comments have been added to the code , Let's mainly talk about the main composition :
- 1. scene (Scene) constitute : The scene is mainly divided into grid models (Mesh) And light source (Light). Mesh model is mainly used to construct the geometry structure in the scene , We can build a whole frame structure with various geometric problems , The material is more like web Style in , Build color for Geometry , Transparency, etc. . The other is the light source , The light source is equivalent to that we add light and shade to the above mesh model , When we add a stronger light source to it , It should be brighter . stay 3D In structure , Different lighting has different shading effects , To show the three-dimensional sense of space . In the code, we create the corresponding grid model Mesh And light source (Light), Add to Scene To build
- The camera (Camera): The camera mainly provides a perspective for the mechanism in the scene . The scenario has been built as 3D Model of , and 3D The structure is a three-dimensional scene , The human eye can't see every side in a straight line , So what we offer here Camera It provides a viewing angle , Through different camera angles , We can go from different places , See different directions of the three-dimensional structure from different directions of the line of sight , The effect of different distances . It's like we actually use cameras , We're going to take a picture , You need to choose different positions and angles .
- Renderers (Render): Through the above scenes and cameras, we have built a virtual three-dimensional scene , The position and angle of the camera are also set , Then the rest is to take photos . Taking pictures is like taking pictures in two dimensions web Display on the plane 3D The stereoscopic effect of a picture in a certain angle of view . When we change our perspective , The renderer will not have different projection effects .
Refer to the rendering process diagram at the end of the following text :

3. Component is introduced
We already know about it threejs A construction process and rendering process . With the example above , The composition of the whole program is shown in the figure below ( Reference pictures ):

In the example above , We built a..., using these components threejs Of 3d application , And the follow-up study is mainly carried out around each structure in the component .
4. threejs Animation
threejs There are two kinds of animation : 1. api Periodic animation provided ,2. Animation based on manual operation
api The cycle animation provided is mainly by cycle , Refresh or change some attributes regularly , Such as rotation angle . We can use js Timer implementation , You can also use requestAnimationFrame The implementation of the .
Animation based on manual operation , Mainly in response to the use of user operations , According to the result of user operation , To transform and refresh certain attributes . For example, in the example above , We use an action that responds to actual user actions , The object will rotate according to the actual drag . Above we use an operation library provided by the official example :
https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js
5. Reference material
Official documents : https://threejs.org
threejs Chinese net : Three.js course
边栏推荐
- LM08丨网格系列之网格反转(精)
- 图扑软件通过 CMMI5 级认证!| 国际软件领域高权威高等级认证
- Connect timed out of database connection
- web254
- 数字转excel的字符串坐标
- 【刷题】字符统计【0】
- Introduction to kubernetes resource objects and common commands (II)
- Aardio - 阴影渐变文字
- [getting started] input n integers and output the smallest K of them
- String coordinates of number to excel
猜你喜欢
![[staff] high and low octave mark (the notes in the high octave mark | mark range are increased by one octave as a whole | low octave mark | mark range are decreased by one octave as a whole)](/img/ff/ebd936eaa6e57b1eabb691b0642957.jpg)
[staff] high and low octave mark (the notes in the high octave mark | mark range are increased by one octave as a whole | low octave mark | mark range are decreased by one octave as a whole)

【无标题】
![[redis] it takes you through redis installation and connection at one go](/img/ca/89cb18f0eeb835f021d6a2489681a1.png)
[redis] it takes you through redis installation and connection at one go

OJ input and output exercise

Set up file server Minio for quick use

凸印的印刷原理及工艺介绍

一套十万级TPS的IM综合消息系统的架构实践与思考

【批处理DOS-CMD-汇总】扩展变量-延迟变量cmd /v:on、cmd /v:off、setlocal enabledelayedexpansion、DisableDelayedExpansion

【入门】截取字符串

7-26 word length (input and output in the loop)
随机推荐
[MySQL learning notes 28] storage function
力扣每日一题-第31天-1790.仅执行一次字符串交换能否使两个字符串相等
Source code analysis of open source API gateway APIs IX
Aardio - 自己构造的getIconHandle的方法
【入门】输入整型数组和排序标识,对其元素按照升序或降序进行排序
Gru of RNN
On June 30, 2022, the record of provincial competition + national competition of Bluebridge
Microsoft stream - how to modify video subtitles
Android screen adaptation (using constraintlayout), kotlin array sorting
empirical study and case study
初学者如何正确理解google官方建议架构原则(疑问?)
力扣每日一题-第31天-202.快乐数
postgresql源码学习(26)—— Windows vscode远程调试Linux上的postgresql
[getting started] input n integers and output the smallest K of them
P4 安装bmv2 详细教程
谈谈数字化转型的几个关键问题
防“活化”照片蒙混过关,数据宝“活体检测+人脸识别”让刷脸更安全
How to get a SharePoint online site created using the office365 group template
[getting started] extract non repeating integers
Saving db4i depth camera pictures with MATLAB