Home Web Front-end JS Tutorial ThreeJS implements starry sky particle movement effect example sharing

ThreeJS implements starry sky particle movement effect example sharing

Jan 18, 2018 pm 02:00 PM
javascript threejs move

This article mainly introduces the use of 3D engine threeJS to realize the starry sky particle movement effect in detail for Hejia. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

three.js is a third-party WebGL library written in JavaScript. Provides a lot of 3D display functions. Three.js is a 3D engine that runs in the browser. You can use it to create various three-dimensional scenes, including cameras, light and shadow, materials and other objects.

Download address: http://threejs.org/

First create an HTML file and introduce the three.js engine package.


<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8">
  <title>Three.js实现3D空间粒子效果</title>
  <style type="text/css">
   body{
    background-color:#000000;
    margin:0px;
    overflow:hidden;
   }
  </style>
  <script src="scripts/three.js"></script>
 </head>
 <body >
 </body>
</html>
Copy after login

Declare global variables


//定义应用所需的组件:相机,场景,渲染器
 var camera, scene, renderer;
 //跟踪鼠标的位置
 var mouseX = 0, mouseY = 0;
 //定义存储粒子的数组
 var particles = [];
Copy after login

Camera:

In OpenGL (WebGL), there are two cameras, perspective projection and orthographic projection, in the way objects in three-dimensional space are projected into two-dimensional space.
Perspective projection is a method in which objects closer to the viewpoint are larger and objects farther away are drawn smaller. This is consistent with the way we see objects in daily life.
Orthographic projection is to draw objects in a uniform size regardless of the distance between them and the viewpoint. In fields such as architecture and design, objects need to be drawn from all angles, so this kind of projection is widely used.
In Three.js, you can also specify cameras in perspective projection and orthographic projection.

Scene:

A scene is a three-dimensional space. Use the [Scene] class to declare an object called [scene].

Renderer:
The process of mapping objects in three-dimensional space to a two-dimensional plane is called three-dimensional rendering. Generally speaking, we call the rendering operation a renderer.

Data initialization


//数据初始化
 function init(){
  //相机参数:
  //四个参数值分别代表:视野角:fov 纵横比:aspect 相机离视体最近的距离:near 相机离视体最远的距离:far
  camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 4000 );
  //设置相机位置,默认位置为:0,0,0. 
  camera.position.z = 1000;

  //声明场景
  scene = new THREE.Scene();
  //将相机装加载到场景
  scene.add(camera);

   //生成渲染器的对象
   renderer = new THREE.CanvasRenderer();
  //设置渲染器的大小
  renderer.setSize( window.innerWidth, window.innerHeight );
  //追加元素
  document.body.appendChild(renderer.domElement);
  //调用自定义的生成粒子的方法
  makeParticles();
  //添加鼠标移动监听
  document.addEventListener(&#39;mousemove&#39;,onMouseMove,false);
  //设置间隔调用update函数,间隔次数为每秒30次
  setInterval(update,1000/30);
 }
Copy after login

Camera initialization instructions:

 Perspective projection is used in the example. var camera = new THREE.PerspectiveCamera( fov , aspect , near , far );
In perspective projection, objects in the field called the visual volume will be made into a projection map. The apparent volume is specified through the following 4 parameters.
 View angle: fov
Aspect ratio: aspect
The closest distance between the camera and the view volume: near
The furthest distance between the camera and the view volume: far

 Set the camera position:

To set the camera position coordinates and the center coordinates of the field of view, press


 //设置相机的位置坐标
    camera.position.x = 100;
    camera.position.y = 20;
    camera.position.z = 50;
Copy after login

Method to set. Like this method, the following method can also be used
  camera.position.set(100,20,50);

In addition, you can also set the upward direction of the camera, the center of the field of view, etc.
Set the upward direction of the camera to the positive direction: 


camera.up.x = 0;
camera.up.y = 0;
camera.up.z = 1;
Copy after login

Set the center of the camera's field of view

Use the [lookAt] method to set the center of the camera's field of view. The parameter of "lookAt()" is an object whose attributes include center coordinates "x", "y" and "z".
The "lookAt()" method is not only used to set the center coordinates of the viewpoint. For the camera attributes set before to have actual effect, the [lookAt] method also needs to be called.


Other projection methods

In Three.js, there are various The class is used to implement cameras such as perspective projection, orthographic projection or compound projection (perspective projection and orthographic projection).


var camera = THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) //正投影
var camera = THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) //複合投影
Copy after login

Renderer

Create a CanvasRenderer object. This is an ordinary 2D canvas object. In the example, we add it to the body tag . Otherwise we wouldn't see it. We want it to fill the entire browser window, so we set its size to window.innerwidth and window.innerheight.

Mouse monitoring

Use the custom function makeParticles() to create particles and add a mousemove listener to them to track the position of the mouse. Finally we create an interval to call the update function 30 times a second.
The definition in the update function is as follows:


function update() {
    updateParticles();
    renderer.render( scene, camera );
  }
Copy after login

Function that generates particles


//定义粒子生成的方法
  function makeParticles(){
    
    var particle,material;
    //粒子从Z轴产生区间在-1000到1000
    for(var zpos=-1000;zpos<1000;zpos+=20){
      //we make a particle material and pass through the colour and custom particle render function we defined. 
      material = new THREE.ParticleCanvasMaterial( { color: 0xffffff, program: particleRender } );
      //生成粒子
      particle = new THREE.Particle(material);
      //随即产生x轴,y轴,区间值为-500-500
      particle.position.x = Math.random()*1000-500;
      particle.position.y = Math.random()*1000-500;
      //设置z轴
      particle.position.z = zpos;
      //scale it up a bit
      particle.scale.x = particle.scale.y = 10;
      //将产生的粒子添加到场景,否则我们将不会看到它
      scene.add(particle);
      //将粒子位置的值保存到数组
      particles.push(particle);
    }
  }
Copy after login

math .random() returns a floating point number between 0 and 1, which we multiply by 1000, giving us a number between 0 and 1000. We then subtract 500, which gives us a number between -500 and 500. We can also define a function that generates a random value within the range like this


function randomRange(min, max) { 
  return Math.random()*(max-min) + min; 
}
Copy after login

Function to draw particles


 //定义粒子绘制函数
  function particleRender( context ) {
    //获取canvas上下文的引用
    context.beginPath();
    // and we just have to draw our shape at 0,0 - in this
    // case an arc from 0 to 2Pi radians or 360º - a full circle!
    context.arc( 0, 0, 1, 0, Math.PI * 2, true );
    //设置原型填充
    context.fill();
  }
Copy after login

The function that defines particle movement, here is set to the movement speed as the mouse distance from the Y axis is 0 The larger the value of the point, the faster the particles move.


 //移动粒子的函数
  function updateParticles(){
    
    //遍历每个粒子
    for(var i=0; i<particles.length; i++){
      particle = particles[i];
      //设置粒子向前移动的速度依赖于鼠标在平面Y轴上的距离
      particle.position.z += mouseY * 0.1;
      //如果粒子Z轴位置到1000,将z轴位置设置到-1000,即移动到原点,这样就会出现无穷尽的星域效果.
      if(particle.position.z>1000){
         particle.position.z-=2000; 
      }
    }
  }
Copy after login

The function monitors when the mouse moves


 //鼠标移动时调用
  function onMouseMove(event){
    mouseX = event.clientX;
    mouseY = event.clientY;
  }
Copy after login

At this point, the simple effect of space particles has been learned.

The integration code is as follows:


<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Three.js实现3D空间粒子效果</title>
    <style type="text/css">
      body{
        background-color:#000000;
        margin:0px;
        overflow:hidden;
      }
    </style>
    <script src="scripts/three.js"></script>
    <script>
      //定义应用所需的组件:相机,场景,渲染器
      var camera, scene, renderer;
      //跟踪鼠标的位置
      var mouseX = 0, mouseY = 0;
      //定义存储粒子的数组
      var particles = [];
      
      //数据初始化
      function init(){
        //相机参数:
        //四个参数值分别代表:视野角:fov 纵横比:aspect 相机离视体最近的距离:near 相机离视体最远的距离:far
        camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 4000 );
        //设置相机位置,默认位置为:0,0,0. 
        camera.position.z = 1000;

        //声明场景
        scene = new THREE.Scene();
        //将相机装加载到场景
        scene.add(camera);
  
        //生成渲染器的对象
        renderer = new THREE.CanvasRenderer();
        //设置渲染器的大小
        renderer.setSize( window.innerWidth, window.innerHeight );
        //追加元素
        document.body.appendChild(renderer.domElement);
        //调用自定义的生成粒子的方法
        makeParticles();
        //添加鼠标移动监听
        document.addEventListener(&#39;mousemove&#39;,onMouseMove,false);
        //设置间隔调用update函数,间隔次数为每秒30次
        setInterval(update,1000/30);
      }
      
      function update() {
        //调用移动粒子的函数
        updateParticles();
        //重新渲染
        renderer.render( scene, camera );
      }

      //定义粒子生成的方法
      function makeParticles(){
        
        var particle,material;
        //粒子从Z轴产生区间在-1000到1000
        for(var zpos=-1000;zpos<1000;zpos+=20){
          //we make a particle material and pass through the colour and custom particle render function we defined. 
          material = new THREE.ParticleCanvasMaterial( { color: 0xffffff, program: particleRender } );
          //生成粒子
          particle = new THREE.Particle(material);
          //随即产生x轴,y轴,区间值为-500-500
          particle.position.x = Math.random()*1000-500; //math . random()返回一个浮点数在0和1之间
          particle.position.y = Math.random()*1000-500;
          //设置z轴
          particle.position.z = zpos;
          //scale it up a bit
          particle.scale.x = particle.scale.y = 10;
          //将产生的粒子添加到场景
          scene.add(particle);
          //将粒子位置的值保存到数组
          particles.push(particle);
        }
      }

      //定义粒子渲染器
      function particleRender( context ) {
        //获取canvas上下文的引用
        context.beginPath();
        // and we just have to draw our shape at 0,0 - in this
        // case an arc from 0 to 2Pi radians or 360º - a full circle!
        context.arc( 0, 0, 1, 0, Math.PI * 2, true );
        //设置原型填充
        context.fill();
      }

        
      //移动粒子的函数
      function updateParticles(){
        
        //遍历每个粒子
        for(var i=0; i<particles.length; i++){
          particle = particles[i];
          //设置粒子向前移动的速度依赖于鼠标在平面Y轴上的距离
          particle.position.z += mouseY * 0.1;
          //如果粒子Z轴位置到1000,将z轴位置设置到-1000
          if(particle.position.z>1000){
             particle.position.z-=2000; 
          }
        }
      }
      
      //鼠标移动时调用
      function onMouseMove(event){
        mouseX = event.clientX;
        mouseY = event.clientY;
      }
    </script>
  </head>
  <body onload="init()">
  </body>
</html>
Copy after login

Related recommendations:

HTML5 development example-ThreeJs implementation of particle animation floating flower effect code sharing

three.js drawing a 3D cube tutorial

Three.js implements 3D map instance sharing

The above is the detailed content of ThreeJS implements starry sky particle movement effect example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
Can the appdata folder be moved to the D drive? Can the appdata folder be moved to the D drive? Feb 18, 2024 pm 01:20 PM

Can the appdata folder be moved to the D drive? With the increasing popularity of computer use, more and more users' personal data and applications are stored on the computer. In Windows operating system, there is a specific folder called appdata folder, which is used to store user's application data. Many users wonder whether this folder can be moved to the D drive or other disks for data management and security considerations. In this article, we will discuss this problem and provide some solutions. First, let me

Stop or allow this PC to access your mobile device on Windows 11 Stop or allow this PC to access your mobile device on Windows 11 Feb 19, 2024 am 11:45 AM

Microsoft changed the name of PhoneLink to MobileDevice in the latest Windows 11 version. This change allows users to control computer access to mobile devices through prompts. This article explains how to manage settings on your computer that allow or deny access from mobile devices. This feature allows you to configure your mobile device and connect it to your computer to send and receive text messages, control mobile applications, view contacts, make phone calls, view galleries, and more. Is it a good idea to connect your phone to your PC? Connecting your phone to your Windows PC is a convenient option, making it easy to transfer functions and media. This is useful for those who need to use their computer when their mobile device is unavailable

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

6000 mAh silicon negative battery! Xiaomi 15Pro upgrade leaked again 6000 mAh silicon negative battery! Xiaomi 15Pro upgrade leaked again Jul 24, 2024 pm 12:45 PM

According to news on July 23, blogger Digital Chat Station broke the news that the battery capacity of Xiaomi 15 Pro has been increased to 6000mAh and supports 90W wired flash charging. This will be the Pro model with the largest battery in Xiaomi’s digital series. Digital Chat Station previously revealed that the battery of Xiaomi 15Pro has ultra-high energy density and the silicon content is much higher than that of competing products. After silicon-based batteries are tested on a large scale in 2023, second-generation silicon anode batteries have been identified as the future development direction of the industry. This year will usher in the peak of direct competition. 1. The theoretical gram capacity of silicon can reach 4200mAh/g, which is more than 10 times the gram capacity of graphite (the theoretical gram capacity of graphite is 372mAh/g). For the negative electrode, the capacity when the lithium ion insertion amount reaches the maximum is the theoretical gram capacity, which means that under the same weight

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

The new king of domestic FPS! 'Operation Delta' Battlefield Exceeds Expectations The new king of domestic FPS! 'Operation Delta' Battlefield Exceeds Expectations Mar 07, 2024 am 09:37 AM

"Operation Delta" will launch a large-scale PC test called "Codename: ZERO" today (March 7). Last weekend, this game held an offline flash mob experience event in Shanghai, and 17173 was also fortunate to be invited to participate. This test is only more than four months away from the last time, which makes us curious, what new highlights and surprises will "Operation Delta" bring in such a short period of time? More than four months ago, I experienced "Operation Delta" in an offline tasting session and the first beta version. At that time, the game only opened the "Dangerous Action" mode. However, Operation Delta was already impressive for its time. In the context of major manufacturers flocking to the mobile game market, such an FPS that is comparable to international standards

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

See all articles