In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use three.js to achieve cool acid style 3D page effect". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's idea to study and learn "how to use three.js to achieve cool acid style 3D page effect".
The main content of this paper is to use React+three.js technology stack to load 3D model, add 3D text, add animation, click interaction and so on, and cooperate with style design to realize the acidic style page full of design feeling.
Background
Recently, I have learned some basic knowledge of WebGL and Three.js, so I would like to decorate my home page and summarize some of what I have learned with the latest popular acidic design style. This paper mainly introduces that by using React + three.js technology stack, loading 3D model, adding 3D text, adding animation, clicking interaction and so on, with style design, full of design sense can be realized. Acid style page.
Basic knowledge
Three.js
Three.js is a 3D engine that runs in browsers based on native WebGL encapsulation, which can be used to create a variety of 3D scenes, including cameras, shadows, materials, and other objects. Is a very widely used 3D engine. You can learn more in the official Chinese documentation of three.js.
Acid design
The word acid design is translated from Acid Graphics and originated from acid room music, electronic dance music and hippie culture in the 1990s. In the field of design, this kind of acid aesthetics carries a free proposition, grotesque graphics, bold and distinct color matching, special material texture, with a variety of fonts, forming a unique acid design style.
In short, the bright color combination with high saturation; the colorful black dotted with black and gray background and highly saturated fluorescent colors; liquid metal, glass, aluminum foil plastic and other materials full of futuristic, cool and technological sense; random elements, graphic layout; constant repetition, cutting, combination of geometry and other materials are acidic design style. Acidic style has gradually become popular in music album covers, visual posters, book and film covers, and web design.
Realize the effect
Online preview: https://tricell.fun
Implement 3D model
Scene initialization
? Create a scen
Scene = new THREE.Scene ()
? Initialize the camera
The four parameters of perspective camera PerspectiveCamera are: field of view, aspect ratio, near surface and far surface.
Camera = new THREE.PerspectiveCamera (70, window.innerWidth / window.innerHeight, 0.1,200); / / set the camera position camera.position.set (600,20,200); / / focus the camera to the center of the screen camera.lookAt (new THREE.Vector3 (0,0,0))
? Initialize the light source
Add hemispherical light source HemisphereLight: create a more natural outdoor light source
Light = new THREE.HemisphereLight (0xffffff, 0x444444); light.position.set (0,20,0); scene.add (light); light = new THREE.DirectionalLight (0xffffff); light.position.set (0,20,10); light.castShadow = true;scene.add (light)
Add an ambient AmbientLight:
Var ambiColor = '0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0C0
Add accessibility (optional)
? Add an auxiliary grid
GridHelper can be used to add grid guides or to decorate through GridHelper (size, divisions, colorCenterLine, colorGrid).
Size: grid width, default is 10. Divisions: equal score, default value is 10.
ColorCenterLine: centerline color. The default value is 0x444444.
ColorGrid: gridline color. The default value is 0x888888.
Var grid = new THREE.GridHelper (1000, 100,100, 0x000000, 0x000000); grid.material.opacity = 0.1scape grid.calendar = true;grid.position.set (0,240,0); scene.add (grid)
? Add camera control
Through the camera control OrbitControls, we can zoom, translate and rotate the 3D scene, which essentially changes not the scene, but the parameters of the camera. OrbitControls.js needs to be introduced separately during development.
Controls = new THREE.OrbitControls (camera, renderer.domElement); controls.target.set (0,0,0); controls.update ()
? Add a performance View plug-in
Stats is an auxiliary library developed by Three.js, which is mainly used to detect the number of frames when the animation is running. Stats.js also needs to be introduced separately.
Stats = new Stats (); container.appendChild (stats.dom); loading model
The 3D model of the discus thrower used in this example comes from threedscans.com and is free of charge. Download and use, at the end of this article provides a number of free model download sites, there are more than 200 pages of free models, if you are interested, you can choose your favorite model to download and use. Of course, students with modeling ability can also use professional modeling software such as blender and 3dmax to generate their favorite models.
Load obj or fbx model
The model loading method that requires the introduction of FBXLoader.js or OBJLoader.js,.fbx and .obj formats separately is the same.
/ / var loader = new THREE.FBXLoader (); var loader = new THREE.OBJLoader (); loader.load (model, function (object) {object.traverse (function (child) {if (child.isMesh) {child.castShadow = true; child.receiveShadow = true;}}); object.rotation.y = Math.PI / 2; object.position.set (0,-200,0); object.scale.set (0.32,0.32,0.32) Model = object; scene.add (object);}); load gltf model
GLTFLoader.js needs to be introduced separately, and the method of loading the .gltf format model is slightly different, it is important to note that the traversal object of the model and the final addition to the scene is object.scene rather than object.
Var loader = new THREE.GLTFLoader (); loader.load (model, function (object) {object.scene.traverse (function (child) {if (child.isMesh) {child.castShadow = true; child.receiveShadow = true;}}); object.scene.rotation.y = Math.PI / 2; object.scene.position.set (0,240,0); object.scene.scale.set (0.33,0.33,0.33); model = object.scene Scene.add (object.scene);})
The effect after adding the grid and loading the model is shown in the following figure.
Add turntable animation
Add turntable animation effects by refreshing the page with requestAnimationFrame. Window.requestAnimationFrame () tells the browser that you want to perform an animation and asks the browser to call the specified callback function to update the animation before the next redraw. This method needs to pass in a callback function as an argument, which will be executed before the browser's next redraw.
Function animate () {requestAnimationFrame (animate); / / change the scene's rotation.y as the page is redrawn to rotate scene.rotation.y-= 0.015; renderer.render (scene, camera);} add click interaction
In the Three.js scene, we click on a model to get information about it, or do something else, using Raycaster (Ray casting). The principle is that a beam of radiation is emitted at the location where you click the mouse, and all the objects in the ray are recorded. The basic syntax is Raycaster (origin, direction, near, far), where:
Origin: the starting vector of the ray.
Direction: the direction vector of the ray.
Near: all returned results should be farther than near. The value cannot be negative and the default value is 0.
Far: all returned results should be closer than far. Cannot be less than near. The default value is infinity.
The basic steps of the code realization are as follows: get the coordinates of the mouse on the screen → screen coordinates to standard device coordinates → standard equipment coordinates → to get the world coordinates of the mouse in the scene → according to the world coordinates and the camera to generate ray projection direction unit vector → to create ray projector objects according to ray projection direction unit vectors.
/ declare the raycaster and mouse variables var raycaster = new THREE.Raycaster (); var mouse = new THREE.Vector2 (); onMouseClick = event = > {/ / convert the screen coordinates of the mouse click location to the standard coordinates in threejs, with the center of the screen as the origin, with values ranging from-1 to 1. Mouse.x = (event.clientX / window.innerWidth) * 2-1; mouse.y =-(event.clientY / window.innerHeight) * 2 + 1 / / calculate the raycaster raycaster.setFromCamera (mouse, camera) from the position of the mouse punctuation and the matrix of the current camera; / / get the array set where the raycaster line intersects all models let intersects = raycaster.intersectObjects (scene.children); if (intersects.length > 0) {alert ('HELLO WORLD') / / you can click on different mesh to trigger different interactions, such as: let selectedObj = intersects [0] .object If (selectedObj.name = = 'car') {alert (' car?')}} window.addEventListener ('click', onMouseClick, false); add 3D text
Using TextGeometry (text: String, parameters: Object) to add 3D text, here is a description of the properties that can be set:
Size: font size, usually the height of uppercase letters.
Height: thickness of the text. Weight: the value is normal or bold, indicating whether it is bold or not.
Font: font. Default is helvetiker, which corresponds to the referenced font file.
Style: the value is normal or italics, indicating whether italic
BevelThickness: chamfer thickness.
BevelSize: chamfer width.
CurveSegments: the number of arc segments to make the text curve smoother.
BevelEnabled: Boolean value, whether to use a chamfer, meaning to cut diagonally at the edge.
Var loader = new THREE.FontLoader (); loader.load ('gentilis_regular.typeface.json', function (font) {var textGeo = new THREE.TextGeometry (' HELLO WORLD', {font: font, size: .8, height: .8, curveSegments: .05, bevelThickness: .05, bevelSize: .05, bevelEnabled: true}); var textMaterial = new THREE.MeshPhongMaterial ({color: 0x03c03c}); var mesh = new THREE.Mesh (textGeo, textMaterial) Mesh.position.set (0,3.8,0); scene.add (mesh);})
Optimize
Now the loading of the model has been basically completed, but the volume of the 3D model is generally large. After deployment, I found that the web page loading is very slow, which affects the user experience, and it is very necessary to reduce the model volume. I have been looking for compression tools on the Internet for a long time. It is found that without the need to install large 3D modeling software, using obj2gltf can transform the larger OBJ format model into gltf model and effectively optimize the model volume. Increase the loading speed of web pages.
Installation
Npm install obj2gltf-save
Copy the obj model to the following directory
Node_modules\ obj2gltf\ bin
Execute transcoding instruction
Node obj2gltf.js-I demo.obj-o demo.gltf
If the figure appears similar to the above, transcoding is completed, and compared with the file volume before and after conversion, in this example, the initial file size of kas.obj is 9.7m, the converted file kas.gltf is only 4.6m, and the volume is reduced by half. At this time, the converted model is loaded onto the page, the effect of the model is almost invisible to the naked eye, and the page loading speed is significantly improved.
Obj2gltf can also be used as a library to transform the model in real time through node services, and interested students can learn more through the link at the end of the article.
It is also possible to use 3D modeling software such as blender to manually optimize the model by reducing the number of model faces and reducing the volume, and the optimization effect is more obvious.
Complete code
Var model = require ('@ / assets/models/kas.gltf'); var container, stats, controls;var camera, scene, renderer, light, model;class Kas extends React.Component {render () {return ()} componentDidMount () {this.initThree ();} initThree () {init (); animate (); function init () {container = document.getElementById ('kas'); scene = new THREE.Scene () Scene.fog = new THREE.Fog (0xa0a0a0, 200,200); / / Perspective camera: field of view, aspect ratio, near camera, far camera = new THREE.PerspectiveCamera (70, window.innerWidth / window.innerHeight, 0.1,200); camera.position.set (600,20,200); camera.lookAt (new THREE.Vector3 (0,0,0)) / / hemispherical light source: create a more natural outdoor light source light = new THREE.HemisphereLight (0xffffff, 0x444444); light.position.set (0,20,0); scene.add (light); light = new THREE.DirectionalLight (0xffffff); light.position.set (0,20,10); light.castShadow = true; scene.add (light) / / Ambient var ambiColor ='# 0C0C0C0C0; var ambientLight = new THREE.AmbientLight (ambiColor); scene.add (ambientLight); / / Grid var grid = new THREE.GridHelper (0,100,100,0x000000, 0x000000); grid.material.opacity = 0.1; grid.material.transparent = true; grid.position.set (0,240,0); scene.add (grid) / load gltf model var loader = new THREE.GLTFLoader (); loader.load (model, function (object) {object.scene.traverse (function (child) {if (child.isMesh) {child.castShadow = true; child.receiveShadow = true;}}); object.scene.rotation.y = Math.PI / 2 Object.scene.position.set (0,-240,0); object.scene.scale.set (0.33,0.33,0.33); model = object.scene; scene.add (object.scene);}); renderer = new THREE.WebGLRenderer ({antialias: true, alpha: true}); renderer.setPixelRatio (window.devicePixelRatio); renderer.setSize (window.innerWidth, window.innerHeight) Renderer.setClearAlpha (0); renderer.shadowMap.enabled = true; container.appendChild (renderer.domElement); window.addEventListener ('resize', () = > {camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix (); renderer.setSize (window.innerWidth, window.innerHeight);}, false); stats = new Stats (); container.appendChild (stats.dom) } function animate () {var clock = new THREE.Clock () requestAnimationFrame (animate); var delta = clock.getDelta (); scene.rotation.y-= 0.015; renderer.render (scene, camera); stats.update ();} / add click events / / declare raycaster and mouse variables var raycaster = new THREE.Raycaster (); var mouse = new THREE.Vector2 () Function onMouseClick (event) {/ / calculates the location of the point needed by the raycaster through the mouse click position, with the center of the screen as the origin, with values ranging from-1 to 1. Mouse.x = (event.clientX / window.innerWidth) * 2-1; mouse.y =-(event.clientY / window.innerHeight) * 2 + 1 / calculate raycaster raycaster.setFromCamera (mouse, camera) from the position of the mouse punctuation and the matrix of the current camera; / / get the array set where the raycaster line intersects all models var intersects = raycaster.intersectObjects (scene.children); if (intersects.length > 0) {alert ('HELLO WORLD')}} window.addEventListener (' click', onMouseClick, false);}} other design elements
This article mainly introduces the loading of 3D elements, due to the limited space and time of the article (the blogger is too lazy?) the implementation of other elements is not explained in detail (maybe later there will be time to summarize and sort out the maybe) students interested in reading the following excellent articles of other great gods.
Fluid background
Static liquid background map can be realized through SVG filter, you can read "Creating Patterns With SVG Filters" to achieve dynamic fluid background, you can use Three.js combined with native GLSL implementation, you can refer to the "CodePen Shader Template" example to achieve.
Metal, neon, fault effects and other acidic effects fonts can read my article "only CSS a few steps to achieve cyberpunk 2077 style visual effects", you can also use design generation, due to time constraints, the metal effect text in this project and the text in the banner header picture are generated using the online art font generation website, interested students can try to design by themselves.
Further optimization in the future
# todo acid style liquid background implementation.
# todo 3D model liquid metal effect.
Three.js excellent case recommendation
Finally, I recommend several amazing three.js projects to experience and learn together, whether it is page interaction, visual design or performance optimization, you can learn a lot from it.
Github home page: 3D Earth real-time display of the world's popular warehouses.
Kodeclubs: low-face 3D city third-person Mini Game.
Sneaker display: 720 degree sneaker dynamic display.
Sand sculpture dance: sand sculpture animal dancer.
Zenly software: Zenly App Chinese homepage.
Thank you for reading, the above is the content of "how to use three.js to achieve cool acid style 3D page effect". After the study of this article, I believe you have a deeper understanding of how to use three.js to achieve cool acid style 3D page effect. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.