当前位置:网站首页>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
边栏推荐
- Significance and measures of source code encryption
- base64
- Office365 - how to use stream app to watch offline files at any time
- LM08丨网格系列之网格反转(精)
- slice扩容机制分析
- [kv260] generate chip temperature curve with xadc
- 【力扣10天SQL入门】Day10 控制流
- Aardio - [problem] the problem of memory growth during the callback of bass Library
- 防“活化”照片蒙混过关,数据宝“活体检测+人脸识别”让刷脸更安全
- ContentType所有类型对比
猜你喜欢

She is the "HR of others" | ones character

Microsoft stream - how to modify video subtitles

038 network security JS

SQL number injection and character injection

0 basic introduction to single chip microcomputer: how to use digital multimeter and precautions

LSTM of RNN

软键盘高度报错

window c盘满了

STM32 uses esp01s to go to the cloud, mqtt FX debugging

Latex table
随机推荐
源代码加密的意义和措施
事务方法调用@Transactional
【网站架构】一招搞定90%的分布式事务,实打实介绍数据库事务、分布式事务的工作原理应用场景
Differential: definition of total differential, partial derivative, gradient
The H5 page has set the font thickness style, but the wechat access style in Huawei mobile phone doesn't take effect?
How outlook puts together messages with the same discussion
Day5: scanner object, next() and nextline(), sequential structure, selection structure, circular structure
Why some people earn nearly 10billion a year, while others earn 3000 a month: the details you ignore actually make the most money
[staff] key number (key number identification position | key number marking list | a major key identification principle | F, C, G position marking ascending | F major key identification principle | B
The Windows C disk is full
数字转excel的字符串坐标
力扣每日一题-第31天-202.快乐数
[getting started] enter the integer array and sorting ID, and sort its elements in ascending or descending order
Li Kou daily question - day 31 -202 Happy number
038 network security JS
Gdip - hatchbrush pattern table
Learn the knowledge you need to know about the communication protocol I2C bus
[redis] it takes you through redis installation and connection at one go
STM32 uses esp01s to go to the cloud, mqtt FX debugging
LM08丨网格系列之网格反转(精)