search
HomeWeb Front-endJS TutorialThree.js implements cool 3D cinema example sharing

You can imagine that we are in a room. The room is a cube. If you have a good taste in life, you may put wallpaper in the room. Three.js can easily create a cube and paste textures around it. , put the camera in the cube, and the camera can rotate 360 ​​degrees to simulate a real scene. This article will share with you how to implement a cool 3D cinema using three.js.

Convert to code:

    const path = 'assets/image/'
    const format = '.jpg'
    const urls = [
      `${path}px${format}`, `${path}nx${format}`,
      `${path}py${format}`, `${path}ny${format}`,
      `${path}pz${format}`, `${path}nz${format}`
    ]
    const materials = []
    urls.forEach(url => {
      const textureLoader = new TextureLoader()
      textureLoader.setCrossOrigin(this.crossOrigin)
      const texture = textureLoader.load(url)
      materials.push(new MeshBasicMaterial({
        map: texture,
        overdraw: true,
        side: BackSide
      }))
    })
    const cube = new Mesh(new CubeGeometry(9000, 9000, 9000), new MeshFaceMaterial(materials))
    this.scene.add(cube)
  • CubeGeometry creates an oversized cube

  • MeshFaceMaterial attaches texture to the cube, due to the perspective It is inside the cube, so side: BackSide

2. Particle effect

A 3D model is composed of points, lines, and surfaces, and each part of the model can be traversed Points, convert each point into a geometric model, attach texture to it, copy the position of each point, and use these geometric models to reconstruct a model with only points. This is the basic principle of particle effects.

this.points = new Group()
    const vertices = []
    let point
    const texture = new TextureLoader().load('assets/image/dot.png')
    geometry.vertices.forEach((o, i) => {
      // 记录每个点的位置
      vertices.push(o.clone())
      const _geometry = new Geometry()
     // 拿到当前点的位置
      const pos = vertices[i]
      _geometry.vertices.push(new Vector3())
      const color = new Color()
      color.r = Math.abs(Math.random() * 10)
      color.g = Math.abs(Math.random() * 10)
      color.b = Math.abs(Math.random() * 10)
      const material = new PointsMaterial({
        color,
        size: Math.random() * 4 + 2,
        map: texture,
        blending: AddEquation,
        depthTest: false,
        transparent: true
      })
      point = new Points(_geometry, material)
      point.position.copy(pos)
      this.points.add(point)
    })
    return this.points
  • new Group creates a group, which can be said to be a collection of particles

  • ##Set particles and positions through point.position.copy(pos) , the coordinates are the same as the position of the corresponding point in the model

3. Click event processing

The click event of three.js requires the use of a ray caster (Raycaster). To facilitate understanding, please look at a picture first:

Three.js implements cool 3D cinema example sharing##Raycaster emits a ray, and intersectObject monitors the object hit by the ray

this.raycaster = new Raycaster()

// 把你要监听点击事件的物体用数组储存起来
this.seats.push(seat)

onTouchStart(event) {
    event.preventDefault()
    event.clientX = event.touches[0].clientX;
    event.clientY = event.touches[0].clientY;
    this.onClick(event)
  }

  onClick(event) {
    const mouse = new Vector2()
    mouse.x = ( event.clientX / this.renderer.domElement.clientWidth ) * 2 - 1
    mouse.y = - ( event.clientY / this.renderer.domElement.clientHeight ) * 2 + 1;
    this.raycaster.setFromCamera(mouse, this.camera)
   // 检测命中的座位
    const intersects = this.raycaster.intersectObjects(this.seats)
    if (intersects.length > 0) {
        intersects[0].object.material = new MeshLambertMaterial({
            color: 0xff0000
        })
    }
  }

    intersects.length > 0 means that the ray hits a certain geometry
  • Lazy only implements the click implementation on the mobile side. If you want to see how to implement it on PC, please see thee. js official website
  • 4. Initial use of shaders

Shaders are divided into vertex shaders and fragment shaders, written in GLSL language, and are a kind of GPU The language of communication, here I only talk about how to use

const vertext = `
   void main()
    {
    gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
  `

const fragment = `
    uniform vec2 resolution;
    uniform float time;

    vec2 rand(vec2 pos)
    {
    return fract( 0.00005 * (pow(pos+2.0, pos.yx + 1.0) * 22222.0));
    }
    vec2 rand2(vec2 pos)
    {
    return rand(rand(pos));
    }

    float softnoise(vec2 pos, float scale)
    {
    vec2 smplpos = pos * scale;
    float c0 = rand2((floor(smplpos) + vec2(0.0, 0.0)) / scale).x;
    float c1 = rand2((floor(smplpos) + vec2(1.0, 0.0)) / scale).x;
    float c2 = rand2((floor(smplpos) + vec2(0.0, 1.0)) / scale).x;
    float c3 = rand2((floor(smplpos) + vec2(1.0, 1.0)) / scale).x;

    vec2 a = fract(smplpos);
    return mix(
    mix(c0, c1, smoothstep(0.0, 1.0, a.x)),
    mix(c2, c3, smoothstep(0.0, 1.0, a.x)),
    smoothstep(0.0, 1.0, a.y));
    }

    void main(void)
    {
    vec2 pos = gl_FragCoord.xy / resolution.y;
    pos.x += time * 0.1;
    float color = 0.0;
    float s = 1.0;
    for(int i = 0; i <p>5. Halo effect</p><h2 id="Since-it-is-a-simulated-cinema-I-want-to-make-a-projector-to-simulate-the-light-emitted-by-the-projector"> Since it is a simulated cinema, I want to make a projector to simulate the light emitted by the projector. </h2><pre class="brush:php;toolbar:false"> // 光晕效果必须设置alpha = true
 const renderer = this.renderer = new WebGLRenderer({alpha: true, antialias: true})

 let textureFlare = new TextureLoader().load('assets/image/lensflare0.png')
      let textureFlare3 = new TextureLoader().load('assets/image/lensflare3.png')
      let flareColor = new Color(0xffffff)
      let lensFlare = new LensFlare(textureFlare, 150, 0.0 , AdditiveBlending, flareColor)
      lensFlare.add(textureFlare3, 60, 0.6, AdditiveBlending);
      lensFlare.add(textureFlare3, 70, 0.7, AdditiveBlending);
      lensFlare.add(textureFlare3, 120, 0.9, AdditiveBlending);
      lensFlare.add(textureFlare3, 70, 1.0, AdditiveBlending);
      lensFlare.position.set(0, 150, -85)

    The main light is still simulated by lensflare0.png
  • textureFlare3 sets the range of the halo
  • Related recommendations:

JS Library Three.js Basics Introduction

Three.js How to Create a Scene

3D photo wall based on three.js and WeChat

The above is the detailed content of Three.js implements cool 3D cinema example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

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 Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment