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 realize 3D Particle dynamic effect based on three.js

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to achieve the dynamic effect of 3D particles based on three.js, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!

I. background

Particle special effect is a production module developed by a variety of three-dimensional software to simulate water, fire, fog, gas and other effects in reality. the principle is to combine countless single particles to make them show a fixed shape, through controllers and scripts to control their overall or individual motion, the simulation shows a real effect. Three.js is a third-party library of WebGL written in JavaScript. Three.js provides rich API to help us achieve 3D dynamic effects. This paper mainly introduces how to use three.js to achieve particle transition effects, as well as the basic mouse interaction.

II. Implementation steps

1. Create a rendered scene scene

Scene is actually equivalent to a three-dimensional space, used to carry and display everything we define, including cameras, objects, lights, and so on. In the actual development, in order to facilitate observation, you can add some auxiliary tools, such as grid, axis and so on.

Scene = new THREE.Scene (); scene.fog = new THREE.Fog (0x05050c, 10,60); scene.add (new THREE.GridHelper (2000, 1)); / / add mesh

two。 Add camera camera

Several cameras are implemented in THREE: PerspectiveCamera, OrthographicCamera (orthographic projection camera), CubeCamera (cube camera or panoramic camera) and StereoCamera (3D camera). This article introduces the PerspectiveCamera that we mainly use:

The visual effect is close to the big and the small.

Configuration parameters PerspectiveCamera (fov, aspect, near, far).

Fov: the visual angle of the camera.

Aspect: the aspect ratio of the visual range of the camera.

Near: the distance relative to the depth cut plane.

Far: the distance relative to the depth cut plane.

Camera = new THREE.PerspectiveCamera (45, window.innerWidth / window.innerHeight, 5,100); camera.position.set (10,-10,-40); scene.add (camera)

3. Add lights needed for scene rendering

The light sources realized in three.js: AmbientLight (ambient light), DirectionalLight (directional light), HemisphereLight (hemispherical light), PointLight (point light), RectAreaLight (plane light source), SpotLight (spotlight) and so on. When configuring the light source parameters, you need to pay attention to the color superposition effect, such as the color of the ambient light will directly affect the current color of the object. There are some differences in the configuration parameters of various light sources. Here are two kinds of light sources that will be used in this case.

Let ambientLight = new THREE.AmbientLight (0x000000, 0.4); scene.add (ambientLight); let pointLight = new THREE.PointLight (0xe42107); pointLight.castShadow = true; pointLight.position.set (- 10,-5,-10); pointLight.distance = 20; scene.add (pointLight)

4. Create, export, and load the model file loader

To create a model, you can create it using three.js editor or the basic model generation class of three.js. Relatively complex or special models need to be created using modeling tools (C4D, 3dmax, etc.).

Using three.js editor to create, you can add basic geometry and adjust various parameters (position, color, material, etc.) of the geometry.

Generated using the model class.

Let geometryCube = new THREE.BoxBufferGeometry (1,1,1); let materialCube = new THREE.MeshBasicMaterial ({color: 0x00ff00}); let cubeMesh = new THREE.Mesh (geometryCube, materialCube); scene.add (cubeMesh)

Export the required model file (the model file in obj format is used here).

Load and parse model file data.

Let onProgress = function (xhr) {if (xhr.lengthComputable) {/ / can calculate the model loading progress}}; let onError = function () {}; particleSystem = new THREE.Group (); var texture = new THREE.TextureLoader (). Load ('. / point.png') New THREE.OBJLoader () .load ('. / model.obj', function (object) {/ / object model file data}, onProgress, onError)

5. Convert import to model file to particle system Points

Gets the coordinate values of the model.

Copy the particle coordinate values to the newly created attribute position1, which serves as the final coordinate position of the particle transition effect.

Add a random 3D coordinate value position to the particle system in order to disrupt the position of each particle and set the starting position.

Let color = new THREE.Color ('# ffffff'); let material = new THREE.PointsMaterial ({size: 0.2, map: texture, depthTest: false, transparent: true}); particleSystem= new THREE.Group (); let allCount = 0 for (let I = 0; I < object.children.length) Attributes.position1 +) {let name = object.children.name let _ attributes = object.children.geometry.attributes let count = _ attributes.position.count _ attributes.positionEnd = _ attributes.position.clone () _ attributes.position1 = _ attributes.position.clone () for (let I = 0; I < child * 3) Let particles +) {_ attributes.position1.array [I] = Math.random () * 100-50} let particles = new THREE.Points (object.children [I] .objection, material) particleSystem.add (particles) allCount + = count} particleSystem.applyMatrix (new THREE.Matrix4 (). MakeTranslation

6. Realize the transformation of particle coordinates from position to position 1 through tween animation library

Use TWEEN's ease algorithm to calculate the coordinate position of each particle for each change. The time from the initial position to the end position is set to 2s (customizable). After each calculation, you need to set the position property of attributes to true to remind the scene that it needs to be updated. In the next rendering, render will use the latest calculated values for rendering.

Let pos = {val: 1}; tween = new TWEEN.Tween (pos). To ({val: 0}, 2500) .room( TWEEN.Easing.Quadratic.InOut) .onUpdate (callback); tween.onComplete (function () {console.log ('transition completed complete')}) tween.start (); function callback () {let val = this.val; let particles = particleSystem.children; for (let I = 0) I < particles.length; iTunes +) {let _ attributes = partitions [I] .geometry.attributes let name = partitions [I] .name if (name.indexOf ('_') =-1) {let positionEnd = _ attributes.positionEnd.array let position1 = _ attributes.position1.array let count = _ attributes.position.count for (let j = 0; j < count * 3) Val +) {_ attributes.position.array [j] = position1 [j] * val + positionEnd [j] * (1-val)}} _ attributes.position.needsUpdate = true / / Settings Update}}

7. Add render scene render

Create a container.

Define the render renderer and set the parameters.

Add the renderer to the container.

Custom rendering function render, in which we use TWEEN.update to update the status of the model.

Call the custom circular animation execution function animate, and use the requestAnimationFrame method to render frame by frame.

Let container = document.createElement ('div'); document.body.appendChild (container); renderer = new THREE.WebGLRenderer ({antialias: true, alpha: true}); renderer.setPixelRatio (window.devicePixelRatio); renderer.setClearColor (scene.fog.color); renderer.setClearAlpha (0.8); renderer.setSize (window.innerWidth, window.innerHeight); container.appendChild (renderer.domElement) / / add webgl renderer function render () {particleSystem.rotation.y + = 0.0001; TWEEN.update (); particleSystem.rotation.y + = (mouseX + camera.rotation.x) * .00001; camera.lookAt (new THREE.Vector3 (- 10,-5,-10) controls.update (); renderer.render (scene, camera) } function animate () {/ / start cycle rendering animation requestAnimationFrame (animate); render ();}

8. Add mouse operation event to realize angle control

We can also add mouse operation events to achieve angle control, where winX and winY are respectively half of the width and height of window. Of course, the specific coordinates can be calculated according to your own needs. The specific effect is shown in the figure below.

Document.addEventListener ('mousemove', onDocumentMouseMove, false); function onDocumentMouseMove (event) {mouseX = (event.clientX-winX) / 2; mouseY = (event.clientY-winY) / 2;}

III. Optimization scheme

1. Reduce the number of particles

As the number of particles increases, it will be very time-consuming to calculate the position and size of each particle, which may cause animation stutters or fake death of the page, so we can reduce the number of particles as much as possible when building the model. can effectively improve performance.

In the above example, we can change the fineness of the derived model to get a different number of particle systems. When the number of particles reaches hundreds of thousands or even millions, we can feel the obvious stutter phenomenon when the animation is loaded. This is mainly due to the low fps. The specific comparison effect is shown below, the number of particles on the left is 300000, and the number of particles on the right is 60, 000. You can clearly see that the frame jump on the left is obvious. The right side is basically in a relatively smooth state.

two。 GPU rendering is adopted.

Write meta shader code, use webgl to provide hardware 3D acceleration for canvas, and browsers can render pages more smoothly. At present, most devices already support this method. It should be noted that on low-end devices, due to hardware devices, the rendering speed may not be as fast as that based on cpu computing.

The above is all the contents of the article "how to achieve the dynamic effect of 3D particles based on three.js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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