当前位置:网站首页>Threejs opening
Threejs opening
2022-07-01 04:13:00 【Nanchen_ forty-two】
One 、Three.js Chapter one 、 Newbie on the road
( One )、 Geometry Geometry
- Square geometry :new THREE.BoxGeometry.BoxGeometry
new THREE.BoxGeometry.BoxGeometry(100, 100, 100); // Create a cube geometry object Geometry
The parameter is ( Long , wide , high )
Code var box=new THREE.BoxGeometry(100,100,100); By constructor THREE.BoxGeometry() Created a length, width and height 100 The cube , By constructor name BoxGeometry You can also guess the meaning of this constructor , utilize new Keyword operation constructor can create an object , This is all Javascript Basic knowledge of language , as for THREE.BoxGeometry() What is a constructor? You don't have to care , Just like you use the front end JQuery Just look up the official documents like the library , You can put the code THREE.BoxGeometry(100,100,100) The first parameter in is changed to 50, Refresh the browser to view the rendering of the box after the data is changed , You can see that it is no longer a cube with the same length, width and height , It's an ordinary cuboid .
You can also replace the box code above with the following code , You will find that you will render a sphere effect .
( Two )、 Sphere geometry object new THREE.SphereGeometry
var geometry = new THREE.SphereGeometry(60, 40, 40);
( 3、 ... and )、 texture of material Material
Code var material=new THREE.MeshLambertMaterial({color:0x0000ff}); By constructor THREE.MeshLambertMaterial() Created a material object that can be used for cubes , The argument to the constructor is an object , Object contains color 、 Transparency, etc , In this case, only color is defined color, Color attribute value 0x0000ff It means blue , You can change the color value to 0x00ff00, You can see the green cube effect , The color value representation used here is 16 Base number RGB Three primary color model .
// Point source
var point = new THREE.PointLight(0xffffff);
point.position.set(300, 400, 500); // Position of point light source
// Parameter is ( Left , On , Right )
scene.add(point); // Add point lights to the scene
To put it bluntly, it is the color of each position
( Four )、 The light source Light
Code var point=new THREE.PointLight(0xffffff); By constructor THREE.PointLight() Created a point light object , Parameters 0xffffff It defines light intensity , You can try changing the parameter to 0x444444, Refresh the browser and you will see the surface color of the cube darken , That makes sense , In real life, the light intensity is lower , The surrounding scenery is naturally dim ,three.js Engine pair WebGL Illumination model algorithms are encapsulated , You don't need to know computer graphics , You can call directly three.js Light source correlation API Create a light source object directly , Just like you use ordinary 3D modeling and rendering software , It's just that there's one more Javascript Programming languages .
// The ambient light
var ambient = new THREE.AmbientLight(0xfec);
scene.add(ambient);
( 5、 ... and )、 The camera Camera
Code var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000); By constructor THREE.OrthographicCamera() Creates an orthophoto camera object , What is? “ Orthographic projection ”, What is? “ Camera object ”, Everyone's base is different , Maybe you don't understand , Maybe you understand , If it's not clear, it's still that sentence , Don't delve into it at first , Change a parameter test to see the visual effect, and you will have certain perceptual knowledge .
camera.position.set(200, 300, 200); and camera.lookAt(scene.position); It defines the position and direction of the camera , You can change camera.position.set(200,300,200);
Parameter redefined camera position , Take the first parameter, which is x The coordinates are from 200 Change to 250, You'll find that the angle of the cube on the screen has changed , It's like the same person in your life , But you take pictures from different angles , The effect of the display must be different . These specific parameter details can be ignored , At least you know that the camera can zoom to show 3D scenes 、 Viewfinder display for different angles of 3D scene .
( 6、 ... and )、 Object methods and properties
Understand the above program from the perspective of object-oriented programming , Use three.js And using other traditional front ends Javascript Library or framework , Through the constructor provided by the framework, you can create objects , Objects have methods and properties , It's just three.js Is a 3D engine , If you are right about HTML、Javascript Language 、 3D modeling and rendering software can understand the application , Even if you don't know computer graphics and WebGL, Can also learn three.js engine , Create a 3D scene that can be previewed online .
The case source code uses constructors respectively
THREE.Scene()
THREE.OrthographicCamera()
THREE.WebGLRenderer()
Created the scene 、 The camera 、 The total of the three topmost objects of the renderer , Then through the sub objects of the total object 、 Methods and properties , Camera objects and rendered objects are relatively simple , The most complex is the scene object ,new THREE.Mesh(box,material); Using constructors Mesh() Created a mesh model object , The object takes the geometry object with vertex position information and the material object with color information in the above two lines as parameters , After the mesh model is created , You need to use the method of the scene object .add() Add sub objects of 3D scene to the scene ,new THREE.PointLight(0xffffff);、new THREE.AmbientLight(0x444444); Two point lights are defined 、 Ambient objects , Then it is inserted into the scene as a sub object of the scene . scene 、 The camera 、 When the renderer setup is complete , Set the code renderer.render(scene,camera) Put the scene 、 Camera object as renderer object method render() Parameters of , The meaning of this code is equivalent to telling the browser to shoot the created 3D scene object according to the camera placement .
Two 、 Rotate animation 、requestAnimationFrame Periodic rendering
( One )、 Periodic rendering
First look at the code :
/* Create and animate renderer objects */
var renderer = new THREE.WebGLRenderer();
function render() {
renderer.render(scene,camera);// Perform the render operation
mesh.rotateX(0.01);// Every time around y Shaft rotation 0.01 radian
}
// interval 20ms Call functions periodically fun,20ms That is, the refresh rate is 50FPS(1s/20ms), Render per second 50 Time
setInterval("render()",20);
/* The following items can be considered as mandatory */
renderer.setSize(width, height);// Set the render area size
renderer.setClearColor(0xffffff, 1); // Set the background color
document.body.appendChild(renderer.domElement); //body Insert... Into the element canvas object
The above code defines a rendering function render(), Function defines three statements , adopt setInterval(“render()”,20); Can achieve m Every interval 20 The function is called once in milliseconds render(), Every time the rendering function is called , perform renderer.render(scene,camera); Render an image , perform mesh.rotateY(0.01); Statement to wrap the cube mesh model around y Shaft rotation 0.01 radian .
( Two )、 Render frequency
Call the rendering method .render() Rendering frequency cannot be too low , Such as execution setInterval(“render()”,200); interval 200 Call the rendering function to render once in milliseconds , Equivalent to rendering per second 5 Time , You will feel more stuck . The rendering frequency should not be too low , It can't be too high , If it is too high, the hardware resources of the computer cannot keep up . Generally, the rendering method is called .render() The rendering frequency of rendering is controlled at per second 30~60 Time , Human visual effects are normal , You can also take into account the rendering performance .
( 3、 ... and )、 function requestAnimationFrame()
threejs Animation effect , Used setInterval() function , In development , In order to make better use of browser rendering , You can use functions requestAnimationFrame() Instead of setInterval() function ,requestAnimationFrame() and setInterval() Both are browsers window Object method .
Of course , Although they are all browsers window Object method , There must be a difference , Keep looking down .
requestAnimationFrame() Parameter is the function name of the function to be called ,requestAnimationFrame() Calling a function is not an immediate call, but a request to the browser to execute a function , When it will be executed is up to the browser , Generally, by default 60FPS The frequency of , About every 16.7ms Call once requestAnimationFrame() Function specified by method ,60FPS It's an ideal situation , If the rendered scene is more complex or the hardware performance is limited, it may be lower than this frequency .
It can be used in this way , There is no need to setInterval()
function render() {
renderer.render(scene,camera);// Perform the render operation
mesh.rotateY(0.01);// Every time around y Shaft rotation 0.01 radian
requestAnimationFrame(render);// Request to execute render function again render
}
render();
( Four )、 Rotate evenly
When actually executing the program , Probably requestAnimationFrame(render) The requested function does not necessarily follow the ideal 60FPS Frequency execution , The time interval between two rendering functions is not necessarily the same , If the rotation command is executed rotateY Different time intervals , The rotational motion is not uniform , To solve this problem, you need to record the time interval between the execution of the drawing function .
Just replace the following rendering function with the original one ,
rotateY() The parameter is 0.001t, It also means the interval between two calls to the rendering function to perform rendering operations t In milliseconds , The cube rotates 0.001t radian , Obviously, the angular velocity of the cube is 0.001 Radians per millisecond (0.0001 rad/ms = 1 rad/s = 180 degree /s).
var renderer = new THREE.WebGLRenderer();
let T0 = new Date();// Last time
function render() {
let T1 = new Date();// Current time
let t = T1 - T0;// Time difference
T0 = T1;// Assign this time to the last time
requestAnimationFrame(render);
renderer.render(scene, camera);// Perform the render operation
mesh.rotateY(0.001 * t);// Rotational angular velocity 0.001 Radians per millisecond
}
render();
CPU and GPU The time to execute an instruction is nanoseconds ns level , Compared to milliseconds ms It's low 6 An order of magnitude , Therefore, it is generally unnecessary to consider the time occupied by several timing statements in the rendering function , Unless you're writing to the nanosecond ns Standard clock program at the level of .
3、 ... and 、 Mouse operation 3D scene
( One )OrbitControls.js
- Introduce controls
<script src="./three.js-master/examples/js/controls/OrbitControls.js"></script>
OrbitControls.js Control supports left, middle and right mouse button operation and keyboard direction key operation
Just take an example to demonstrate :
var renderer = new THREE.WebGLRenderer();
let T0 = new Date();// Last time
function render() {
let T1 = new Date();// Current time
let t = T1 - T0;// Time difference
T0 = T1;// Assign this time to the last time
renderer.render(scene, camera);// Perform the render operation
// mesh.rotateY(0.001 * t);// Rotational angular velocity 0.001 Radians per millisecond
}
render();
/* ? Set mouse events */
var controls = new THREE.OrbitControls(camera,renderer.domElement);// Create a control object
controls.addEventListener('change', render);
The effect is as follows :
Of course , The mouse also contains the following operations ( There will be no demonstration here , Those who are interested can try it by themselves ):
- The zoom : rolling —— Middle mouse button
- rotate : Drag the —— Left mouse button
- translation : Drag the —— Right mouse button
( Two )、requestAnimationFrame() usage
If threejs Passed in code requestAnimationFrame() Implementation of rendering method of renderers render() Periodic call of , When passed OrbitControls When the operation changes the state of the camera , There's no need to go through controls.addEventListener(‘change’, render) Listen for mouse events and call render functions , because requestAnimationFrame() You're going to call render functions all the time .
It's very simple , Just like before setinterval() equally , There is no need to call rendering functions through events , Use it directly requestAnimationFrame() that will do . Here's an example :
function render() {
renderer.render(scene,camera);// Perform the render operation
requestAnimationFrame(render);// Request to execute render function again render
}
render();
var controls = new THREE.OrbitControls(camera,renderer.domElement);// Create a control object
// Have gone through requestAnimationFrame(render); Periodically render function , There's no need to monitor mouse events any more render function
// controls.addEventListener('change', render)
The effect is consistent with the above figure ;
Pay attention not to use at the same time in development requestAnimationFrame() or controls.addEventListener('change', render) Call the same function , It's going to conflict .
边栏推荐
- [TA frost wolf \u may- hundred people plan] 2.4 traditional empirical lighting model
- Qt development experience tips 226-230
- 6. zigzag transformation
- JMeter学习笔记2-图形界面简单介绍
- Redis(七)优化建议
- Coinbase in a bear market: losses, layoffs, stock price plunges
- 214. minimum palindrome string
- [recommended algorithm] C interview question of a small factory
- Web components series (VIII) -- custom component style settings
- Inventory the six second level capabilities of Huawei cloud gaussdb (for redis)
猜你喜欢
线程常用方法与守护线程
【TA-霜狼_may-《百人计划》】1.1 渲染流水线
Programs and processes, process management, foreground and background processes
[recommended algorithm] C interview question of a small factory
[TA frost wolf \u may- hundred people plan] 2.4 traditional empirical lighting model
25.K个一组翻转链表
431. encode n-ary tree as binary tree DFS
[human version] Web3 privacy game in the dark forest
Recommend the best product development process in the Internet industry!
跳槽一次涨8k,5年跳了3次...
随机推荐
Task04 | statistiques mathématiques
【历史上的今天】6 月 30 日:冯·诺依曼发表第一份草案;九十年代末的半导体大战;CBS 收购 CNET
Qt开发经验小技巧226-230
166. fractions to decimals
什么是uid?什么是Auth?什么是验证器?
JD intelligent customer service Yanxi intention system construction and intention recognition technology introduction
一些小知识点
[leetcode skimming] February summary (updating)
283. move zero
Account sharing technology enables the farmers' market and reshapes the efficiency of transaction management services
CF1638E colorful operations
Spock单元测试框架介绍及在美团优选的实践___第一章
Usage of AfxMessageBox and MessageBox
208. implement trie (prefix tree)
基于Unet的环路滤波
NFT:使用 EIP-2981 開啟 NFT 版稅之旅
431. encode n-ary tree as binary tree DFS
Recommend the best product development process in the Internet industry!
Browser top loading (from Zhihu)
431. 将 N 叉树编码为二叉树 DFS