当前位置:网站首页>Use three JS realize the 'ice cream' earth, and let the earth cool for a summer
Use three JS realize the 'ice cream' earth, and let the earth cool for a summer
2022-07-01 22:46:00 【Front end technology station】
Preface
The weather has been a bit hot recently , The road to the laboratory is a bit long , walking , Xiao Bao felt that his soul had been heated out of his body . Go back to the lab , Turn on the air conditioner , Eat ice cream , Sit still for a few minutes , Just feel the taste of the soul again , Ge you is lying on the small bed in the laboratory , The mind starts to soar , There are 10000 ways to keep a small bag cool , But mother earth , She is getting hotter , Who can cool her down ?
Lie down. Lie down , I fell asleep , Xiao Bao dreamed that one day in the future , Human beings are super developed , Can travel through time and space , But the cost of development is also huge , Mother earth is overwhelmed , The heat exceeds the standard , But there is nothing we can do , Scientists finally came up with an old idea , Wrap a circle of the earth in ice , Physical cooling . This is very frightening , When Xiao Bao wakes up , I sat for a while , Decided to make a Ice cream earth , It's not just a joke , It is also a kind of reflection and warning , Protect the earth , Everyone is responsible. .
Online experience ( Support PC And mobile terminals ): Ice cream Earth online preview
Source warehouse : Ice cream earth
Share an interview question bank web Front end interview question bank VS java Back end interview question bank
ThreeJS Basics —— To achieve a rotating sphere
Three.js
It's a browser running 3D
engine , You can use it to create a variety of 3D scenes , Including cameras 、 Light and shadow 、 Materials and other objects , Everyone should have seen more or less Three
The legend of . This is the first time the small bag has been used Three
, So the bag will surround Ice cream earth The details of the implementation start with .
Let's take a look at it first Three
The basic elements of the framework ( Picture source : Three.js course )
Three
The three most important objects in are scene 、 Cameras and renderers . The scene is where the model is placed 、 A lighted field ; The camera sets how and from what angle to view the scene , The renderer renders the effect into the web page . These three concepts are not difficult to understand , Let's implement these three objects in code .
// scene const scene = new THREE.Scene();// Perspective camera const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000);// Renderers const renderer = new THREE.WebGLRenderer();// Set the render area size renderer.setSize(window.innerWidth, window.innerHeight);// body Insert... Into the element canvas object document.body.appendChild(renderer.domElement);// Set the background color renderer.setClearColor("hotpink");// Perform the render operation Specify the scene 、 Camera as a parameter renderer.render(scene, camera);
Three
There are many kinds of cameras in , This article mainly uses perspective camera (PerspectiveCamera
), The principle is similar to what the human eye sees , There are four parameters :
PerspectiveCamera( fov : Number, aspect : Number, near : Number, far : Number )
fov
: Indicates the angle range that can be seen , The value is angle , Similar to the human perspective .aspect
: Represents the aspect ratio of the rendering window , If there is only one pagecanvas
, Its value is usually set to the aspect ratio of the web page viewportnear/far
:near/far
Represent the near shear plane and the far shear plane of the camera respectively
The words are difficult to understand , Please refer to the figure below :
Open the browser , See what will be rendered ? At present, you can only see the full pink pages , This is because... Is not added in the current scenario 3D
Model object .
Next, let's add a sphere model , As the base of the earth .
const cRadius = 100;const geometry = new THREE.SphereBufferGeometry(
cRadius,
cRadius * 6.4,
cRadius * 6.4);
SphereBufferGeometry
yes Three
To implement the API
, There are so many parameters , Only the first three parameters are introduced here
radius
: Radius of spherewidthSegments
: Number of segments along the longitudeheightSegments
: Number of segments along the weft line
Add a material to the sphere Material
, At present, we only add one color attribute .
// Material object Materialconst material = new THREE.MeshLambertMaterial({ color: 0x0000ff,
});
Render mesh body Mesh
, And add it to the scene Scene
in .
// Mesh body Mesh, The two parameters are geometry and material const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);
Reopen web site , You don't see a sphere , Or a vast expanse of solitude , What is the justice in ?
Three
The initial position of the camera defaults to (0,0,0)
, Camera focus defaults to Z
Axis negative half axis direction , The radius of the sphere is 100
, That is, the camera is currently inside the sphere , So we need to adjust the camera position .
// Set the camera position camera.position.set(0, 0, 220);// Set the direction of camera focus camera.lookAt(scene.position);
Dangdang Dangdang , You can successfully see a black sphere in the web page , Well, it's a little strange , What we set up is 0x0000ff
Color , How can a black model be displayed ?
Xiao Bao thought hard : All things have no color , Color is the reflection of light . In the whole scene , At present, there is no light source , So the directional lights are added below (DirectionalLight
) And point lights (PointLight
)
Directional light is light emitted in a specific direction , Its performance is similar to the infinite sunshine , This article uses it to simulate sunlight . A point light source is a light source that emits from a point in all directions , Use it to increase the overall brightness .
// Declare directional light const light = new THREE.DirectionalLight();// Set the position of the directional light source light.position.set(0, 0, 1);// Add a directional light source to the scene scene.add(light);// Declare point lights const point = new THREE.PointLight(0xeeeeee);// Sets the position of the point light point.position.set(400, 200, 300);// Add point lights to the scene scene.add(point);
The stereoscopic effect doesn't look obvious , Don't worry , Next, let's move the sphere . Next , Add a... To the sphere z
Axis and y
Rotation of shaft .
const createAnimRotation = () => { const speed = 0.005;
sphere.rotation.z += speed / 2;
sphere.rotation.y += speed;
};const render = () => {
createAnimRotation();
renderer.render(scene, camera);
requestAnimationFrame(render);
};
render();
Because the sphere is symmetrical , The rotation does not seem obvious , If you especially want to see the rotation effect , Can be SphereBufferGeometry
Temporarily replace with BoxBufferGeometry
.
ThreeJS texture —— Realize the rotating earth
The above has successfully realized the earth , Next, let's dress the earth . This paper realizes the ice cream earth , Therefore, the small bag directly puts an ice cream coat on it .
Three
You can map a texture map onto geometry , We will not explore the specific mapping principle , The idea of mapping can be seen in the following figure .
Select a texture map of the ice cream earth , Use the following code to achieve texture mapping effect .
// Texture loader object const textureLoader = new THREE.TextureLoader();const textureSurface = textureLoader.load( "https://s3-us-west-2.amazonaws.com/s.cdpn.io/249663/world-surface.jpg");// Set texture map const material = new THREE.MeshLambertMaterial({ map: textureSurface });
The ice cream earth with only normal mapping looks very good , But there is room for further beautification ,Three
Provides a specular map , Use a specular map , There will be highlights .
const textureSpecular = textureLoader.load( "https://s3-us-west-2.amazonaws.com/s.cdpn.io/249663/world-specular.jpg");const material = new THREE.MeshPhongMaterial({ map: textureSurface, specularMap: textureSpecular, shininess: 80, // The brightness of the highlight });
Although the frame number of motion picture recording is too low , You can still see some highlighted areas .
Three
Environment maps are also provided , Environment mapping can add surface detail , Make the 3D model more three-dimensional .
const textureElevation = textureLoader.load( "https://s3-us-west-2.amazonaws.com/s.cdpn.io/249663/world-elevation.jpg");const material = new THREE.MeshPhongMaterial({ map: textureSurface, normalMap: textureElevation, specularMap: textureSpecular, shininess: 80,
});
Stereoscopic effect is available , But the details seem to be inexhaustible , The color is a little dim , Not in line with the style of ice cream .
Packet continues to view the document , There are... In the environment map normalScale
attribute , You can set the color depth , Reduce the corresponding attribute value to 0.5,0.5
.
sphere.material.normalScale.set(0.5, 0.5);
Interactive ice cream earth
Add some interactive effects to the earth :
When the mouse is near , The earth zooms in ; When the mouse is far away , Earth shrinking
The earth rotates with the mouse
The above dynamic effects can be achieved by moving the camera position . First, set the maximum positive and negative rotation angle of the earth as 270
.
// Define dynamic objects let mouseX = 0;let mouseY = 0;const moveAnimate = { coordinates(clientX, clientY) { const limit = 270; const limitNeg = limit * -1;
mouseX = clientX - window.innerWidth / 2;
mouseY = clientY - window.innerHeight / 2;
mouseX = mouseX >= limit ? limit : mouseX;
mouseX = mouseX <= limitNeg ? limitNeg : mouseX;
mouseY = mouseY >= limit ? limit : mouseY;
mouseY = mouseY <= limitNeg ? limitNeg : mouseY;
}, onMouseMove(e) {
moveAnimate.coordinates(e.clientX, e.clientY);
},
};document.addEventListener("mousemove", moveAnimate.onMouseMove);
Calculated from the above events mouseX
And mouseY
Value , stay render
Function , modify camera
The location of .
camera.position.x += (mouseX * -1 - camera.position.x) * 0.05;
camera.position.y += (mouseY - camera.position.y) * 0.05;
camera.lookAt(scene.position);
The mobile terminal monitors synchronously touchmove
event , The mobile phone can also see the dynamic effect of the ice cream earth .
const moveAnimate = { onTouchMove(e) { const touchX = e.changedTouches[0].clientX; const touchY = e.changedTouches[0].clientY;
moveAnimate.coordinates(touchX, touchY);
},
};document.addEventListener("touchmove", moveAnimate.onTouchMove);
add to loading effect
The loading of textures takes some time , So add a transition loading
effect .
loading
Effect use the effect in the text in front of the small bag to realize the jump .
.loader { display: flex; color: white; display: flex; justify-content: center; align-items: center; font-size: 5em; width: 100%; height: 100%; font-family: "Baloo Bhaijaan", cursive;
}.loader span { text-shadow: 0 1px #bbb, 0 2px #bbb, 0 3px #bbb, 0 4px #bbb, 0 5px #bbb, 0 6px
transparent, 0 7px transparent, 0 8px transparent, 0 9px transparent, 0
10px 10px rgba(0, 0, 0, 0.4); text-shadow: 0 1px #bbb, 0 2px #bbb, 0 3px #bbb, 0 4px #bbb, 0 5px #bbb, 0 6px
#bbb, 0 7px #bbb, 0 8px #bbb, 0 9px #bbb, 0 50px 25px rgba(0, 0, 0, 0.2); transform: translateY(-20px);
}
Three
Provides LoadingManager
, Its function is to process and track the loaded and pending data . When all loaders are loaded , Would call LoadingManager
Upper onLoad
event .
So we define a LoadingManager
, When triggered onLoad
After the event , Remove the load flag from the page .
const loadingScreen = { scene: new THREE.Scene(), camera: new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000
), // Remove the function that loads the flag
removeText() { const loadingText = document.querySelector("#canvas-loader"); if (loadingText.parentNode) {
loadingText.parentNode.removeChild(loadingText);
}
},
};// Initialize loader let loadingManager = new THREE.LoadingManager();// Listen to the loader onLoad event loadingManager.onLoad = () => {
loadingScreen.removeText();
isLoaded = true;
};// Texture map loader passed in loadingManagerconst textureLoader = new THREE.TextureLoader(loadingManager);
Reference link
Three Chinese document
Afterword
I am a Battlefield bag , A rapidly growing small front end , I hope I can make progress with you .
If you like small bags , Can be in Nuggets Pay attention to me , You can also focus on my little official account. —— Small bag learning front end .
Come on all the way , Rush to the future !!!
An early end to the epidemic Peace has returned to the world
Share an interview question bank web Front end interview question bank VS java Back end interview question bank
边栏推荐
- 小红书Scheme跳转到指定页面
- 详解Volatile关键字
- 陈天奇的机器学习编译课(免费)
- 倒置残差的理解
- C#/VB.NET 给PDF文档添加文本/图像水印
- Relationship and difference between enterprise architecture and project management
- Explain kubernetes network model in detail
- Configure filter
- Smart micro mm32 multi-channel adc-dma configuration
- C#/VB. Net to add text / image watermarks to PDF documents
猜你喜欢
详解ThreadLocal
Sonic cloud real machine learning summary 6 - 1.4.1 server and agent deployment
详解JMM
Pytorch sharpening chapter | argmax and argmin functions
Fully annotated SSM framework construction
YOLOv5.5 调用本地摄像头
leetcode - 287. 寻找重复数
13th Blue Bridge Cup group B national tournament
【MySQL】索引的分类
Object memory layout
随机推荐
牛客月赛-分组求对数和
Measurement of reference loop gain and phase margin
redis配置文件中常用配置详解[通俗易懂]
MySQL view exercise
微信开放平台扫码登录[通俗易懂]
Mysql——》Innodb存储引擎的索引
Appium automated testing foundation - Supplement: introduction to desired capabilities parameters
Mysql5.7 set password policy (etc. three-level password transformation)
基准环路增益与相位裕度的测量
园区全光技术选型-中篇
QT 使用FFmpeg4将argb的Qimage转换成YUV422P
深度学习--数据操作
RestTemplate 远程调用工具类
Chen Tianqi's machine learning compilation course (free)
【日常训练】326. 3 的幂
好友新书发布,祝贺(送福利)
阿洛迷茫后的思考
MySQL的视图练习题
The fixed assets management subsystem reports are divided into what categories and which accounts are included
Appium自动化测试基础 — APPium安装(一)