当前位置:网站首页>Use three JS make a simple 3D scene
Use three JS make a simple 3D scene
2022-07-03 03:20:00 【Hold the North】
Three.js What is it?
Three.js Is a Running in the browser 3D engine , We can use it to create a series of things we need 3D Animated scene , In short, it is built on the web 3D Model . utilize Three.js You can make a lot of cool 3D Animation , also Three.js You can also use the mouse 、 keyboard 、 Drag and drop events to interact , Add some... To the page 3D Animation and 3D Interaction can produce a better user experience .
Three.js Program structure
It is mainly divided into three structures : scene Scene The camera Camera Renderers Renderer
The whole process of the program is : Load the scene first —— Then the camera —— Last renderer

Understand from the perspective of taking pictures in real life , The cube mesh model and illumination form a virtual three-dimensional scene similar to the object you want to shoot , Camera objects can take pictures just like the cameras you use in your life , Only one is to shoot the real scenery , One is to shoot virtual scenery , When shooting an object, the position and angle of the camera need to be adjusted , The virtual camera also needs to set the projection mode , When you create a 3D scene , The camera is also set up , Just one move away “ Kaka ”, You can take photos through the renderer 
Simply understand the use Three.js do 3D How the engine works , Let's make a simple one today 3D Cube
Cube
First of all, we need to html Introduce in the file three.js, Like introducing others .js File directly , It needs to be downloaded from the official website
here , I use the relative path

Or reference relative path
<!-- Absolute path remote load -->
<script src="http://www.yanhuangxueyuan.com/3D/example/three.js"></script>
<!-- Compressed version -->
<script src="http://www.yanhuangxueyuan.com/3D/example/three.min.js"></script>then , stay body Just insert a code snippet into , The specific code is explained as follows :
<body>
<script>
// Create scene objects Scene
var scene = new THREE.Scene();
// Create a grid model
// var geometry = new THREE.SphereGeometry(60, 40, 40); // Create a sphere geometry object
var geometry = new THREE.BoxGeometry(100, 100, 100); // Create a cube geometry object
var material = new THREE.MeshLambertMaterial({ // Create material objects Material
color: 0x008080 // The color of the cube
});
var mesh = new THREE.Mesh(geometry, material); // Create mesh model objects Mesh
scene.add(mesh); // Put the grid mesh Add the model to the scene
// Lighting settings
// Point source
var point = new THREE.PointLight(0xffffff);
point.position.set(400, 200, 300); // The position of the point light source
scene.add(point); // Add point lights to the scene
// The ambient light
var ambient = new THREE.AmbientLight(0x444444);
scene.add(ambient);
// console.log(scene)
// console.log(scene.children)
// Camera settings
var width = window.innerWidth; // Window width
var height = window.innerHeight; // Window height
var k = width / height; // Window aspect ratio
var s = 200; // Three dimensional scene display range control coefficient , The larger the coefficient , The larger the scope of the display
// Create camera objects
var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
camera.position.set(200, 300, 200); // Set camera position
camera.lookAt(scene.position); // Set camera orientation ( Point to the scene object )
// Create a render object
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);// Set the render area size
renderer.setClearColor(0xb9d3ff, 1); // Set the background color
document.body.appendChild(renderer.domElement); //body Insert... Into the element canvas object
// Perform the render operation Specify the scene 、 Camera as a parameter
renderer.render(scene, camera);
</script>
</body>Show the effect :

Rotate animation
Do it here , Just present a static... On the web page 3D Cube , In order to increase interest and operability , We can encapsulate the rendering operation into a function , use setInterval Let it interval 20ms Periodically call render() Rendering function 、 Constantly refresh
// Rendering function
function render() {
renderer.render(scene,camera);// Perform the render operation
mesh.rotateY(0.01);// Every time around y Shaft rotation 0.01 radian
}
// interval 20ms Call the rendering function periodically render()
setInterval("render()",20);The time unit here is ms,20ms That is, the refresh rate is 50FPS(1s/20ms), namely 1s Internal screen refresh 50 Time ( I believe that little friends who play games are not unfamiliar )
The effect is as follows :

Or through requestAnimationFrame Request to execute render function again render, Render the next frame , This can also achieve constant refresh , The effect of rotation
// Rendering function
let T0 = new Date();// Last time
function render() {
let T1 = new Date();// Current time
let t = T1-T0;// Time difference
console.log(t);// Time interval between two frames Company :ms
T0 = T1;// Assign this time to the last time
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 the next frame
}
render();We can create two temporary variables T1 and T0 Record the time required for this rendering and the last rendering , Then subtract them , You get the time interval between two frames , Found stable in 17ms about ,58 Of fps, Compared with the time period we set ourselves , its fps Higher , There are no limitations
The effect is as follows :

Operate the mouse to rotate and zoom the 3D scene
We have achieved to make the cube move mechanically , Can you control it with a mouse , Let it go to any angle and position we want
First , We also need to introduce a new Threejs Extended controls ——OrbitControls.js, It is called track control , It can be used to realize scene interaction with the mouse , Let the scene move , Controls the rotation of the scene 、 Pan and zoom
<!-- Introduce track control OrbitControls.js -->
<!-- Relative paths -->
<script src="./OrbitControls.js"></script>
<!-- Absolute path -->
<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/examples/js/controls/OrbitControls.js"></script>here , The track control provides a constructor , We create a new constructor , Add another mouse monitoring event , The mouse moves , Trigger rendering function , Cube experience the corresponding effect
// Rendering function
function render() {
renderer.render(scene, camera); // Perform the render operation
}
render();
// Create a control object Camera object camera As a parameter Control can monitor changes in the mouse , Change the properties of the camera object
var controls = new THREE.OrbitControls(camera,renderer.domElement);
// Listening to mouse events , Trigger rendering function , to update canvas Canvas rendering effect
controls.addEventListener('change', render);Show the effect :

In fact, the track control has many properties that can be set , But it is not applied to , For detailed usage, please refer to the official documents : Click to open the link
边栏推荐
- VS 2019配置tensorRT
- docker安装mysql
- Can I use read-only to automatically implement properties- Is read-only auto-implemented property possible?
- Model transformation onnx2engine
- Vs 2019 configuration du moteur de génération de tensorrt
- MySQL practice 45 [SQL query and update execution process]
- MySql实战45讲【索引】
- Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
- 机械臂速成小指南(八):运动学建模(标准DH法)
- float与0比较
猜你喜欢
随机推荐
labelimg生成的xml文件转换为voc格式
Vs Code configure virtual environment
解决高並發下System.currentTimeMillis卡頓
解决高并发下System.currentTimeMillis卡顿
Idea set method call ignore case
labelme标记的文件转换为yolov5格式
900w+ data, from 17s to 300ms, how to operate
Variable declarations following if statements
敏捷认证(Professional Scrum Master)模拟练习题
PAT乙级常用函数用法总结
VS 2019安装及配置opencv
How to limit the size of the dictionary- How to limit the size of a dictionary?
[shutter] monitor the transparency gradient of the scrolling action control component (remove the blank of the top status bar | frame layout component | transparency component | monitor the scrolling
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
Lvgl usage experience
Bigvision code
Summary of determinant knowledge points in Chapter 1 of Linear Algebra (Jeff's self perception)
Basic information of Promethus (I)
Creation and destruction of function stack frame
【AI实战】应用xgboost.XGBRegressor搭建空气质量预测模型(一)





![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)


