Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Three.js to realize 3D Creative Page of Spring Festival in the year of the Tiger

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use Three.js to realize the 3D creative page of the Spring Festival in the year of the Tiger". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Three.js to realize the 3D creative page of the year of the Tiger.

Background

This paper uses React + Three.js technology stack to realize interesting 3D creative pages. The knowledge contained in this paper mainly includes: the use of two basic materials ShadowMaterial and MeshPhongMaterial, the use of LoadingManager to show the loading progress of the model, the slow animation of OrbitControls, the simple motion tween effect of TWEEN, and so on.

Realize

? Online preview, adapted to mobile: https://dragonir.github.io/3d/

Introduction of resources

GLTFLoader and FBXLoader are used to add to the model, OrbitControls user lens track control, and TWEEN to generate motion tweens.

Import * as THREE from "three"; import {GLTFLoader} from "three/examples/jsm/loaders/GLTFLoader"; import {FBXLoader} from "three/examples/jsm/loaders/FBXLoader"; import {OrbitControls} from "three/examples/jsm/controls/OrbitControls"; import {TWEEN} from "three/examples/jsm/libs/tween.module.min.js"; scene initialization

This part is mainly used to initialize the scene and parameters. You can click on the link at the end of the article to read my previous article. I will not repeat it in this article.

Container = document.getElementById ('container'); renderer = new THREE.WebGLRenderer ({antialias: true}); renderer.setPixelRatio (window.devicePixelRatio); renderer.setSize (window.innerWidth, window.innerHeight); renderer.shadowMap.enabled = true;container.appendChild (renderer.domElement); / / scene scene = new THREE.Scene (); scene.background = new THREE.TextureLoader (). Load (bgTexture); / / atomization effect scene.fog = new THREE.Fog (0xdddddd, 100,120) / / camera camera = new THREE.PerspectiveCamera (60, window.innerWidth / window.innerHeight, 1000); camera.position.set (100,100,100); camera.lookAt (new THREE.Vector3 (0,0,0)); / / directional light const cube = new THREE.Mesh (new THREE.BoxGeometry (0.001, 0.001, 0.001), new THREE.MeshLambertMaterial ({color: 0xdc161a}); cube.position.set (0,0,0); light = new THREE.DirectionalLight (0xffffff, 1) Light.position.set (20, 20, 8); light.target = cube;scene.add (light); / / Ambient const ambientLight = new THREE.AmbientLight (0xffffff); scene.add (ambientLight); / / Spotlight const spotLight = new THREE.SpotLight (0xffffff); spotLight.position.set (- 20, 20,-2); scene.add (spotLight); Fog scene atomization

In this example, the function of loading the model from far and near and changing the color from white to color when the page is opened is achieved through Fog. Fog class defines linear fog, and the density of fog increases linearly with distance, that is, the atomization effect of objects in the scene varies linearly with distance.

Constructor: Fog (color, near, far).

Color attribute: represents the color of the fog, such as red, the distant object in the scene is black, the nearest object in the scene is its own color, and the color between the farthest and nearest object is a mixture of the color of the object itself and the color of the fog.

Near attribute: indicates the minimum distance to apply the atomization effect. Objects whose distance from the active camera length is less than near will not be affected by fog.

Far attribute: indicates the maximum distance to apply the atomization effect. Objects longer than far from the active camera will not be affected by fog.

Create the ground

The background image is used in this example. I need a material that not only shows the background transparently but also produces shadows to generate the ground, so I use the ShadowMaterial material.

Var planeGeometry = new THREE.PlaneGeometry (100,100); var planeMaterial = new THREE.ShadowMaterial ({opacity: .5}); var plane = new THREE.Mesh (planeGeometry, planeMaterial); plane.rotation.x =-0.5 * Math.PI;plane.position.set (0,-8,0); plane.receiveShadow = true;scene.add (plane); ShadowMaterial Shadow material

This material can receive shadows, but is completely transparent in other ways.

Constructor: ShadowMaterial (parameters: Object)

Parameters: (optional) an object that defines the appearance of a material, with one or more properties.

Special attributes:

.isShadowmaterial [Boolean]: used to check whether this class or derived class is a shadow material. The default is true. Because it is usually used for internal optimization, the value of this property should not be changed.

.transparency [Boolean]: defines whether this material is transparent. The default is true.

Create a magic array

In the tiger? The bottom ground creates a cool rotating self-luminous circular magic array.

Cycle = new THREE.Mesh (new THREE.PlaneGeometry (40,40), new THREE.MeshPhongMaterial ({map: new THREE.TextureLoader (). Load (cycleTexture), transparent: true}); cycle.rotation.x =-0.5 * Math.PI;cycle.position.set (0,-9,0); cycle.receiveShadow = true;scene.add (cycle)

The map of the magic array:

MeshPhongMaterial mesh material

A material used for glossy surfaces with specular highlights. The material uses a non-physical Blinn-Phong model to calculate reflectivity.

Constructor: MeshPhongMaterial (parameters: Object)

Parameters: (optional) an object that defines the appearance of a material, with one or more properties.

Special attributes:

Emissive [Color]: the radiant (light) color of a material, which is basically an inherent color that is not affected by other light. The default is black.

.emissiveMap [Texture]: sets the radiometric (glowing) map. The default is null. The radiation map color is adjusted by the radiation color and intensity. If you have a radiation map, be sure to set the radiation color to something other than black. .emissiveIntensity [Float]: the intensity of radiation. Adjust the glow color. The default is 1.

Shininess [Float]: the higher the highlight of the specular, the brighter the value. The default value is 30.

.specular [Color]: the specular color of the material. The default value is the color Color of 0x111111. This defines the glossiness of the material and the color of the gloss.

.specularMap [Texture]: specular map values affect the specular highlight and how much the environment map affects the surface. The default is null.

Unlike the Lambertian model used in MeshLambertMaterial, this material simulates glossy surfaces with specular highlights, such as painted wood. When shading is calculated using the Phong shading model, the shadow of each pixel is calculated, and the result of this model is more accurate than the Gouraud model used by MeshLambertMaterial, but at the expense of some performance.

MeshStandardMaterial and MeshPhysicalMaterial also use this shading model. When using this material on MeshStandardMaterial or MeshPhysicalMaterial, performance is usually higher, but at the expense of some graphics precision.

Text model

Use FBXLoader to load a 3D text model of the words Kung Hi Fat-Tsai and year-on-year peace.

Const fbxLoader = new FBXLoader (); fbxLoader.load (textModel, mesh = > {mesh.traverse (child = > {if (child.isMesh) {meshes.push (mesh); child.castShadow = true; child.receiveShadow = true; / / adjust the metalness, roughness, color and other styles of materials child.material.metalness = .2; child.material.roughness = .8; child.material.color = new THREE.Color (0x111111) }); mesh.position.set (4,6,-8); mesh.rotation.set (- 80,0,0); mesh.scale.set (.32, .32, .32); group.add (mesh);})

? Bilibili 3D text generation tutorial Portal: iBlender Chinese version plug-in foreigners teach you to use Chinese fonts Font 3D Chinese And Japanese Characters Blender plug-in tutorial

Tiger model

The tiger model is in gltf format. In the process of loading the model with GLTFLoader, it is found that there are? Bug,loader cannot read the total value of the model volume, so the generic loader LoadingManager is used to manage the model loading progress.

Const manager = new THREE.LoadingManager (); manager.onStart = (url, loaded, total) = > {}; manager.onLoad = () = > {}; manager.onProgress = async (url, loaded, total) = > {if (Math.floor (loaded / total * 100) = 100) {this.setState ({loadingProcess: Math.floor (loaded / total * 100)});} else {this.setState ({loadingProcess: Math.floor (loaded / total * 100)});}; const gltfLoader = new GLTFLoader (manager) GltfLoader.load (tigerModel, mesh = > {mesh.scene.traverse (child = > {if (child.isMesh) {child.castShadow = true; child.material.metalness = 0; child.material.roughness = .8; child.material.transparent = true; child.material.side = THREE.DoubleSide; child.material.color = new THREE.Color (0xffffff);}}); mesh.scene.rotation.y = Math.PI * 9 / 8 Mesh.scene.position.set (0,-4,2); mesh.scene.scale.set (.75, .75, .75); / /? Load the model's own animation let meshAnimation = mesh.animations [0]; mixer = new THREE.AnimationMixer (mesh.scene); let animationClip = meshAnimation; let clipAction = mixer.clipAction (animationClip). Play (); animationClip = clipAction.getClip (); group.add (mesh.scene); scene.add (group)})

LoadingManager Loader Manager

Its function is to process and track loaded and pending data. If the hardening manager is not set manually, the default global instance loader manager is created and used for the loader. In general, the default load manager is sufficient, but sometimes you need to set up a separate loader, for example, when you want to display separate load bars for objects and textures.

Construction method: LoadingManager (onLoad: Function, onProgress: Function, onError: Function)

OnLoad: optionally, this function will be called after all loaders have finished loading.

OnProgress: optionally, this function will be called when each project is completed.

OnError: optionally, this function is called when a loader encounters an error.

Attributes:

.onStart [Function]: called at the beginning of the load. Parameter: the number of current url;itemsLoaded add-ons for the items loaded by url; the total number of add-ins required by itemsTotal. This method is not defined by default.

.onload [Function]: this function will be called when all items are loaded. By default, this method is not defined unless it is passed in the constructor.

.onProgress [Function]: this method loads each item and is called when the loading is complete. Parameter: the number of current url;itemsLoaded add-ons for the items loaded by url; the total number of add-ins required by itemsTotal. By default, this method is not defined unless it is passed in the constructor.

.onError [Function]: this method will be called when any item is loaded in error. Parameter: the url of the wrong item loaded by url. By default, this method is not defined unless it is passed in the constructor.

Add a motion tween for lens movement

After the model is loaded, the camera is realized by using TWEEN.js. Mobile to achieve roaming, that is, when you open the page to see the model from far and near gradually larger animation effect.

Const Animations = {animateCamera: (camera, controls, newP, newT, time = 2000, callBack) = > {var tween = new TWEEN.Tween ({x1: camera.position.x, y1: camera.position.y, Z1: camera.position.z, x2: controls.target.x, y2: controls.target.y, Z2: controls.target.z,}) Tween.to ({x1: newP.x, y1: newP.y, Z1: newP.z, x2: newT.x, y2: newT.y, Z2: newT.z,}, time); tween.onUpdate (function (object) {camera.position.x = object.y1; camera.position.z = object.z1; controls.target.x = object.x2) Controls.target.y = object.y2; controls.target.z = object.z2; controls.update ();}); tween.onComplete (function () {controls.enabled = true; callBack ();}); tween.easing (TWEEN.Easing.Cubic.InOut); tween.start ();},} export default Animations

Call example:

Animations.animateCamera (camera, controls, {x: 0, y: 5, z: 21}, {x: 0, y: 0, z: 0}, 2400, () = > {}); TWEEN.js

Is a tween animation library, can achieve a lot of animation effects. It makes an object slowly change from one state to another in a certain period of time. TWEEN.js is essentially a series of slow function algorithms, which can achieve a lot of effects simply by combining Canvas and Three.js.

Basic use:

Var tween = new TWEEN.Tween ({x: 1}) / / position: {x: 1} .delay / / wait for 100ms.to ({x: 200}, 1000) / / 1s time Execute render method .onComplete (() = > {}) / / Animation complete .onStop (() = > {}) / / Animation stop .start () during x to 200.onUpdate (render) / / change / / enable animation

? To get the animation really moving, you need to call the update method in requestAnimationFrame.

TWEEN.update ()

Ease type:

The most powerful thing about TWEEN.js is that it provides many commonly used types of ease animation, specified by api easing (). As used in the example:

Tween.easing (TWEEN.Easing.Cubic.InOut)

Chain call:

TWEEN.js supports chained calls, such as performing animation B after the end of animation A, so that tweenA.chain (tweenB) uses chained calls to create back-and-forth animation:

Var tweenA = new TWEEN.Tween (position). To ({x: 200}, 1000); var tweenB = new TWEEN.Tween (position). To ({x: 0}, 1000); tweenA.chain (tweenB); tweenB.chain (tweenA); tweenA.start ()

Slow motion of controller

Setting controls.enableDamping to true can turn on the ease effect when the mouse moves the scene, resulting in motion inertia, and 3D is more realistic after opening.

Controls = new OrbitControls (camera, renderer.domElement); controls.target.set (0,0,0); controls.enableDamping = true;controls.maxDistance = 160THREE.OrbitControls parameter control list / / Mouse control whether controls.enabled = true;// focus coordinates controls.target = new THREE.Vector3 (); / / maximum and minimum camera movement distance (PerspectiveCamera depth of field camera) controls.minDistance = 0controls.maxdistance = Infinity / / maximum and minimum mouse zoom size (OrthographicCamera orthographic camera) controls.minZoom = 0 control. MaxZoom = Infinity;// maximum angle of view and angle of view, range is 0 to Math.PIcontrols.minPolarAngle = 0 control. MaxPolarAngle = Math.PI;// horizontal view limit, range [- Math.PI, Math.PI] controls.minAzimuthAngle =-Infinity;controls.maxAzimuthAngle = Infinity / / Inertial sliding, the sliding size defaults to 0.25. If enabled, controls.update () needs to be added to the animation loop function controls.enableDamping = false;controls.dampingFactor = 0.25 true / whether the roller can control the zoom,zoom speed default 1controls.enableZoom = true;controls.zoomSpeed = 1.0 true / whether it can be rotated, the rotation speed controls.enableRotate = true;controls.rotateSpeed = 1.0 pm / whether it can be translated, the default moving speed is 7pxcontrols.enablePan = true / / the pixel value that moves when you click the arrow key controls.keyPanSpeed = 7.0 position / whether or not automatic rotation, automatic rotation speed. By default, 30 laps per second, if it is enabled, then controls.update () needs to be added to the animation loop function controls.autoRotate = false;// when fps is 60 / 30scontrols.autoRotateSpeed = 2.0 per turn / whether the keyboard controls.enableKeys = true;// can be used to control the keys up and down by default controls.keys = {LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40} / / Click the button controls.mouseButtons = {ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT}

Finally, don't forget to add window zoom adaptation methods and requestAnimationFrame update methods.

Function onWindowResize () {camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix (); renderer.setSize (window.innerWidth, window.innerHeight);} function animate () {requestAnimationFrame (animate); renderer.render (scene, camera); let time = clock.getDelta (); / / Tiger mixer & & mixer.update (time); / / Motion Tween TWEEN & & TWEEN.update (); / / Controller controls & & controls.update () / / Magic Array cycle & & (cycle.rotation.z + = .01);}

Loading page 3D text style

3D text style is mainly realized by overlaying multi-layer text-shadow.

.loading {font-size: 64px; color: # FFFFFF Text-shadow: 0 1px 0 hsl (174 hsl 5% hsl), 0 2px 0 hsl (174 3px 5% 6px 75%), 0 3px 0 hsl (174 5% hsl 66%), 0 6px 0 hsl (174 5% minus 62%) 0 7px 0 hsl, 0 8px 0 hsl, 0 5px rgba, 0 1px 3px rgba, 0 3px 5px rgba, 0 5px 10px rgba 0 10px 10px rgba (0penny 0penny .2), 0 20px 20px rgba (0penny 0penny 0penny .3) }

Effect.

The final result is shown in the figure below. If you are interested, you can preview it online and the mobile end has been adapted. By this accelerated little brain axe? Move the picture and laugh to death.

At this point, I believe you have a deeper understanding of "how to use Three.js to achieve the 3D creative page of the year of the Tiger". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report