sroxck

sroxck

ThreeJS Learning Notes

Basic Example#

<script setup>
  import * as three from 'three'

  // Create a scene
  const scene = new three.Scene()

  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )

  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)

  // Create material
  const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
  // Create mesh
  const cube = new three.Mesh(geometry, material)
  // Add mesh to the scene
  scene.add(cube)

  // Set camera position
  camera.position.z = 5
  // Look at
  camera.lookAt(0, 0, 0)

  // Render function
  function animate() {
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    cube.rotation.x += 0.01
    cube.rotation.y += 0.01
    // Render
    renderer.render(scene, camera)
  }
  animate()
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

World Coordinate Helper#

Blue z-axis
Red x-axis
Green y-axis

<script setup>
  import * as three from 'three'

  // Create a scene
  const scene = new three.Scene()

  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )

  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)

  // Create material
  const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
  // Create mesh
  const cube = new three.Mesh(geometry, material)
  // Add mesh to the scene
  scene.add(cube)

  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Look at
  camera.lookAt(0, 0, 0)

  // Add world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  scene.add(axesHelper)

  // Render function
  function animate() {
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    // cube.rotation.x +=0.01
    // cube.rotation.y += 0.01
    // Render
    renderer.render(scene, camera)
  }
  animate()
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

Orbit Controller#

<script setup>
  import * as three from 'three'
  // Import orbit controller
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
  // Create a scene
  const scene = new three.Scene()

  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )

  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)

  // Create material
  const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
  // Create mesh
  const cube = new three.Mesh(geometry, material)
  // Add mesh to the scene
  scene.add(cube)

  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Look at
  camera.lookAt(0, 0, 0)

  // Add world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  scene.add(axesHelper)

  // Create controller, can modify the second parameter to choose which dom to control events
  const controls = new OrbitControls(camera, renderer.domElement)
  // Enable damping, dragging will have inertia
  controls.enableDamping = true
  // Set damping factor
  controls.dampingFactor = 0.04
  // Enable auto-rotation
  controls.autoRotate = true
  // Render function
  function animate() {
    // Update controller
    controls.update()
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    cube.rotation.x += 0.01
    cube.rotation.y += 0.01
    // Render
    renderer.render(scene, camera)
  }
  animate()
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

3D Objects#

This is the base class for most objects in Three.js, providing a series of properties and methods to manipulate objects in 3D space.

Note that you can combine objects using the .add(object) method, which adds the object as a child, but it is best to use Group (as the parent object) for this.

3D Vector Vector3#

Represents coordinates in the x, y, z directions, and you can directly modify the x, y, z properties of the 3D vector.

position: Vector3 Movement Property#

The local coordinate point vector3 coordinates of the object are based on the parent element; if there is no parent element, it is the world coordinates.

<script setup>
  import * as three from 'three'
  // Import orbit controller
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
  // Create a scene
  const scene = new three.Scene()
  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )
  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)
  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)
  // Create material Parent element red, child element green
  const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
  const parentMaterial = new three.MeshBasicMaterial({ color: 0xff0000 })
  // Create mesh
  // Create parent element
  let parentCube = new three.Mesh(geometry, parentMaterial)
  // Create child element
  const cube = new three.Mesh(geometry, material)
  // Add child element to parent element
  parentCube.add(cube)
  // Set parent element's displacement
  parentCube.position.set(-3, 0, 0)
  // Set child element's displacement, based on the parent element
  cube.position.set(3, 0, 0)
  // Add mesh to the scene, only need to add one parent element
  scene.add(parentCube)

  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Look at
  camera.lookAt(0, 0, 0)

  // Add world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  scene.add(axesHelper)

  // Create controller, can modify the second parameter to choose which dom to control events
  const controls = new OrbitControls(camera, renderer.domElement)
  // Enable damping, dragging will have inertia
  controls.enableDamping = true
  // Set damping factor
  controls.dampingFactor = 0.04
  // Enable auto-rotation
  // controls.autoRotate = true
  // Render function
  function animate() {
    // Update controller
    controls.update()
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    // cube.rotation.x +=0.01
    // cube.rotation.y += 0.01
    // Render
    renderer.render(scene, camera)
  }
  animate()
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

scale: Vector3 Scaling Property#

Local scaling of the object, based on the parent element.

<script setup>
  import * as three from 'three'
  // Import orbit controller
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
  // Create a scene
  const scene = new three.Scene()

  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )

  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)

  // Create material
  const material = new three.MeshBasicMaterial({color:0x00ff00})
  const parentMaterial = new three.MeshBasicMaterial({color:0xff0000})
  // Create mesh

  let parentCube = new three.Mesh(geometry,parentMaterial)
  
  const cube = new three.Mesh(geometry,material)
  parentCube.add(cube)
  parentCube.position.set(-3,0,0)
  cube.position.set(3,0,0)
  // Set the cube to enlarge
  cube.scale.set(2,2,2)
  parentCube.scale.set(2,2,2)
  // Add mesh to the scene
   scene.add(parentCube)
  // scene.add(cube)

  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Look at
  camera.lookAt(0,0,0)

  // Add world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  scene.add(axesHelper)
 
  // Create controller, can modify the second parameter to choose which dom to control events
  const controls = new OrbitControls(camera,renderer.domElement)
  // Enable damping, dragging will have inertia
  controls.enableDamping = true
  // Set damping factor
  controls.dampingFactor = .04
  // Enable auto-rotation
  // controls.autoRotate = true
  // Render function
  function animate(){
    // Update controller
    controls.update()
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    // cube.rotation.x +=0.01
    // cube.rotation.y += 0.01
    // Render
    renderer.render(scene,camera)
  }
 animate()
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

Euler Euler Angle Object#

Euler angles specify an axis to rotate the object, with the rotation order following the axis order, defaulting to xyz order.

rotation: Euler Rotation Property#

Local rotation of the object, based on the parent element.

<script setup>
  import * as three from 'three'
  // Import orbit controller
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
  // Create a scene
  const scene = new three.Scene()

  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )

  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)

  // Create material
  const material = new three.MeshBasicMaterial({color:0x00ff00})
  const parentMaterial = new three.MeshBasicMaterial({color:0xff0000})
  // Create mesh

  let parentCube = new three.Mesh(geometry,parentMaterial)
  
  const cube = new three.Mesh(geometry,material)
  parentCube.add(cube)
  parentCube.position.set(-3,0,0)
  cube.position.set(3,0,0)
  // Set the cube to enlarge
  // cube.scale.set(2,2,2)
  // Rotate around the x-axis

  cube.rotation.x = Math.PI/4
  // parentCube.scale.set(2,2,2)
  // Add mesh to the scene
   scene.add(parentCube)
  // scene.add(cube)

  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Look at
  camera.lookAt(0,0,0)

  // Add world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  scene.add(axesHelper)
 
  // Create controller, can modify the second parameter to choose which dom to control events
  const controls = new OrbitControls(camera,renderer.domElement)
  // Enable damping, dragging will have inertia
  controls.enableDamping = true
  // Set damping factor
  controls.dampingFactor = .04
  // Enable auto-rotation
  // controls.autoRotate = true
  // Render function
  function animate(){
    // Update controller
    controls.update()
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    // cube.rotation.x +=0.01
    // cube.rotation.y += 0.01
    // Render
    renderer.render(scene,camera)
  }
 animate()
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

Responsive Canvas and Adaptation#

<script setup>
  import * as three from 'three'
  // Import orbit controller
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
  // Create a scene
  const scene = new three.Scene()

  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )

  // Create a renderer
  const renderer = new three.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)

  // Create material
  const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
  const parentMaterial = new three.MeshBasicMaterial({ color: 0xff0000 })
  // Create mesh

  let parentCube = new three.Mesh(geometry, parentMaterial)

  const cube = new three.Mesh(geometry, material)
  parentCube.add(cube)
  parentCube.position.set(-3, 0, 0)
  cube.position.set(3, 0, 0)
  // Add mesh to the scene
  scene.add(parentCube)
  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Look at
  camera.lookAt(0, 0, 0)

  // Add world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  scene.add(axesHelper)

  // Create controller, can modify the second parameter to choose which dom to control events
  const controls = new OrbitControls(camera, renderer.domElement)
  // Enable damping, dragging will have inertia
  controls.enableDamping = true
  // Set damping factor
  controls.dampingFactor = 0.04
  // Enable auto-rotation
  // controls.autoRotate = true
  // Render function
  function animate() {
    // Update controller
    controls.update()
    // Continue executing in the next frame to achieve continuous animation
    // Move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    // cube.rotation.x +=0.01
    // cube.rotation.y += 0.01
    // Render
    renderer.render(scene, camera)
  }
  animate()
  // Listen for window size changes to re-render the canvas
  window.addEventListener('resize', () => {
    // Reset renderer aspect ratio
    renderer.setSize(window.innerWidth, window.innerHeight)
    // Reset camera aspect ratio
    camera.aspect = window.innerWidth / window.innerHeight
    // Update camera projection matrix
    camera.updateProjectionMatrix()
  })

  let btn = document.createElement('button')
  btn.innerHTML = 'Click'
  btn.style.position = 'absolute'
  btn.style.top = '10%'
  btn.style.left = '50%'
  btn.style.zIndex = '9999'
  document.body.appendChild(btn)

  btn.addEventListener('click', () => {
    // Fullscreen canvas
    renderer.domElement.requestFullscreen()
  })
</script>

<template>
  <div> </div>
</template>

<style scoped></style>

Fullscreen Canvas#

renderer.domElement.requestFullscreen()

The dom.requestFullscreen() method will adjust the current window to fullscreen mode.

Exit Fullscreen#

document.exitFullscreen()

Basic Example Code#

<script setup>
  // Import three
  import * as three from 'three'
  // Import orbit controller
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
  // Create a scene
  const scene = new three.Scene()
  // Create a camera
  const camera = new three.PerspectiveCamera(
    45, // Field of view
    window.innerWidth / window.innerHeight, // Aspect ratio
    0.1, // Near plane
    1000 // Far plane
  )
  // Create a renderer
  const renderer = new three.WebGLRenderer()
  // Set renderer size
  renderer.setSize(window.innerWidth, window.innerHeight)
  // Add renderer to body
  document.body.appendChild(renderer.domElement)
  // Create geometry
  const geometry = new three.BoxGeometry(1, 1, 1)
  // Create material
  const material = new three.MeshBasicMaterial({ color: 0x00ff00 })
  // Create mesh
  const cube = new three.Mesh(geometry, material)
  // Set mesh position
  cube.position.set(3, 0, 0)
  // Add mesh to the scene
  scene.add(cube)
  // Set camera position
  camera.position.z = 5
  camera.position.y = 2
  camera.position.x = 2
  // Camera looks at
  camera.lookAt(0, 0, 0)
  // Create world coordinate helper
  const axesHelper = new three.AxesHelper(5)
  // Add helper to the scene
  scene.add(axesHelper)
  // Create controller, can modify the second parameter to choose which dom to control events
  const controls = new OrbitControls(camera, renderer.domElement) 
  // Enable damping, dragging will have inertia 
  controls.enableDamping = true 
  // Set damping factor
  controls.dampingFactor = 0.04 
  // Enable auto-rotation
  controls.autoRotate = true
  // Render function
  function animate() {
    // Update controller
    controls.update()
    // Continue executing in the next frame to achieve continuous animation, move x and y in each frame to create a rotation animation
    requestAnimationFrame(animate)
    // Set geometry x-axis movement
    cube.rotation.x += 0.01 
    cube.rotation.y += 0.01
    // Render
    renderer.render(scene, camera)
  }
  animate()
  // Listen for window size changes to re-render the canvas
  window.addEventListener('resize', () => {
    // Reset renderer aspect ratio
    renderer.setSize(window.innerWidth, window.innerHeight)
    // Reset camera aspect ratio
    camera.aspect = window.innerWidth / window.innerHeight
    // Update camera projection matrix
    camera.updateProjectionMatrix()
  })

</script>

<template>
  <div></div>
</template>

<style scoped></style>

GUI Tools#

  1. Import

import {GUI} from 'three/examples/jsm/libs/lil-gui.module.min.js'

  1. Use

const gui = new GUI()

  1. Define

Standard definition object

let eventObje = {
    fullScreen: () => {
        document.body.requestFullscreen()
    },
    exitfullScreen: () => {
        document.exitFullscreen()
    }
}
  1. Use
gui.add(eventObje,'fullScreen')
gui.add(eventObje,'exitfullScreen')
  1. Modify Chinese names
gui.add(eventObje, 'fullScreen').name = 'Fullscreen'
gui.add(eventObje, 'exitfullScreen').name = 'Exit Fullscreen'
  1. Loop add
let eventObje = {
    fullScreen: {
        name: 'Fullscreen',
        on: () => {
            document.body.requestFullscreen()
        }
    },
    exitfullScreen: {
        name: 'Exit Fullscreen',
        on: () => {
            document.exitFullscreen()
        }
    }
}
const gui = new GUI()
for (const [key, value] of Object.entries(eventObje)) {
    gui.add({
        [key]: value.on
    }, key).name(value.name)
}
  1. Set cube properties
folder.add(cube.position, 'x').min(-10).max(10).name('x-axis').onChange(val => console.log(val))

min sets the minimum value
max sets the maximum value
step sets the step size
onChange sets the event triggered when changed
onFinishChange sets the event triggered when change is completed

  1. Set material properties
gui.add(material, 'wireframe').name('Wireframe')
gui.addColor(material, 'color').name('Color')
  1. wireframe sets whether to use wireframe mode
  2. addColor sets the color

Using Vertex to Draw a Plane#

Cubes are made up of flat triangles, and triangles are made up of 3 vertices.

  1. Create a plane
    const geo = new three.BufferGeometry()

Use buffer geometry.

  1. Set vertex data
    You need to use a 32-bit float array, vertices are ordered, counterclockwise is the front.

Draw a triangle

const vertices = new Float32Array([
    -1, -1, 0
    1, -1, 0
    1, 1, 0
])

Parameters are the vertex array, one triangle has three vertices, each vertex has x, y, z coordinates.

  1. Set vertex data to geometry
    geo.setAttribute('position', new three.BufferAttribute(vertices, 3))

  2. Set square
    Just need to draw one triangle adjacent to this triangle.

// const vertices = new Float32Array([
//   -1.0, -1.0, 0.0,
//   1.0, -1.0, 0.0,
//   1.0, 1.0, 0.0,
//   1.0,1.0,0.0,
//   -1.0,1.0,0.0,
//   -1.0,-1.0,0.0,
// ])
// Set vertex data to geometry vertex position attribute
// geometry.setAttribute('position', new three.BufferAttribute(vertices, 3))
  1. Use indices

Since two triangles are adjacent, some vertices can actually be shared. The above method has 6 vertices for the square, which can be optimized to 4 using indices.
::: tip
Using indices requires specifying 4 vertex coordinates, which are the 4 points of the square.
:::

// Use indices to draw 4 vertices
const vertices = new Float32Array([
    -1.0, -1.0, 0.0,
    1.0, -1.0, 0.0,
    1.0, 1.0, 0.0,
    -1.0, 1.0, 0.0,
])
// Create indices using 0,1,2 to create one triangle, using 2,3,0 to create another triangle
// Combine to form a square, saving 2 vertices
const indices = new Uint16Array([
    0, 1, 2,
    2, 3, 0
])
// Set indices
geometry.setIndex(new three.BufferAttribute(indices, 1))
geometry.setAttribute('position', new three.BufferAttribute(vertices, 3))

Set Different Materials for Different Faces#

  1. Set vertex groups
// Set two vertex groups
geometry.addGroup(0, 3, 0)
geometry.addGroup(3, 3, 1)
geometry.setAttribute('position', new three.BufferAttribute(vertices, 3))
// When creating the mesh, the material can pass an array, each vertex group corresponds to a material
const material = new three.MeshBasicMaterial({
    color: 0x00ff00,
    side: three.DoubleSide
})
const material2 = new three.MeshBasicMaterial({
    color: 0xff0000,
    side: three.DoubleSide
})
const cube = new three.Mesh(geometry, [material, material2])

Built-in Geometries#

  1. Box Buffer Geometry
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

Constructor
BoxGeometry(width : Float, height : Float, depth : Float, widthSegments : Integer, heightSegments : Integer, depthSegments : Integer)

width — Width on the X-axis, default value is 1.

height — Height on the Y-axis, default value is 1.

depth — Depth on the Z-axis, default value is 1.

widthSegments — (optional) Number of segments in width, default value is 1.

heightSegments — (optional) Number of segments in height, default value is 1.

depthSegments — (optional) Number of segments in depth, default value is 1.

  1. Circle Buffer Geometry
const geometry = new THREE.CircleGeometry( 5, 32 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const circle = new THREE.Mesh( geometry, material );
scene.add( circle );

Constructor
CircleGeometry(radius : Float, segments : Integer, thetaStart : Float, thetaLength : Float)

radius — Radius of the circle, default value is 1.

segments — Number of segments (triangular faces), minimum value is 3, default value is 8.

thetaStart — Starting angle of the first segment, default is 0. (three o'clock position)

thetaLength — Central angle of the circular sector, commonly referred to as “θ” (theta). Default is 2*Pi, making it a complete circle.

  1. Cone Buffer Geometry
const geometry = new THREE.ConeGeometry( 5, 20, 32 );
const material = new THREE.MeshBasicMaterial( {color: 0xffff00} );
const cone = new THREE.Mesh( geometry, material );
scene.add( cone );

Constructor
BoxGeometry(width : Float, height : Float, depth : Float, widthSegments : Integer, heightSegments : Integer, depthSegments : Integer)

width — Width on the X-axis, default value is 1.

height — Height on the Y-axis, default value is 1.

depth — Depth on the Z-axis, default value is 1.

widthSegments — (optional) Number of segments in width, default value is 1.

heightSegments — (optional) Number of segments in height, default value is 1.

depthSegments — (optional) Number of segments in depth, default value is 1.

Other geometries https://www.three3d.cn/docs/index.html?q=geo#api/zh/core/BufferGeometry

Adding Texture Mapping#

When creating a material, pass the map property in the configuration object, with the value being the texture object.

  1. Create a texture loader
    const loader = new three.TextureLoader()
  2. Create a texture object
    const texture = loader.load('./img/texture.png')
  3. Create a material
    const material = new three.MeshBasicMaterial({map: texture})
  4. Set textures
  • Alpha Map

Function: Used to control the transparency of the model's surface (Alpha value). Black areas are fully transparent, white areas are fully opaque, and gray areas are partially transparent.
Usage scenario: Suitable for making partially transparent objects like windows and glass.

  • Light Map

Function: Stores pre-calculated lighting information to reduce the burden of real-time lighting calculations. This texture contains shadow and brightness information.
Usage scenario: Used to improve rendering efficiency in static scenes, suitable for scenes with little lighting change, such as the interiors of buildings.

  • Specular Map

Function: Controls which parts of the model's surface have a specular effect. The brightness values in the specular map determine the reflection intensity of that part of the surface.
Usage scenario: Suitable for models that require fine control over specular areas, such as metallic items, leather, etc.

  • Environment Map

Function: Simulates environmental reflections to achieve environmental reflection effects on the object's surface, making the object appear more realistic.
Usage scenario: Commonly used for highly reflective objects, such as water surfaces, metal spheres, etc.

  • AO Map

Function: Simulates ambient occlusion effects, enhancing the shadows and depth perception of the object's surface. Black areas in the AO map indicate light being occluded (shadow areas), while white areas indicate light not being occluded.
Usage scenario: Suitable for enhancing model details, commonly used in complex models and scenes to increase visual depth and realism.

// Create texture loader
const textureLoader = new THREE.TextureLoader();

// Load textures
const alphaMap = textureLoader.load('path/to/alphaMap.png');
const lightMap = textureLoader.load('path/to/lightMap.png');
const specularMap = textureLoader.load('path/to/specularMap.png');
const envMap = textureLoader.load('path/to/envMap.png');
const aoMap = textureLoader.load('path/to/aoMap.png');

// Create material
const material = new THREE.MeshStandardMaterial({
  color: 0xffffff,
  alphaMap: alphaMap,
  transparent: true,
  lightMap: lightMap,
  specularMap: specularMap,
  envMap: envMap,
  aoMap: aoMap,
  aoMapIntensity: 1.0 // AO map intensity
});

// Create mesh
const geometry = new THREE.BoxGeometry(1, 1, 1);
const mesh = new THREE.Mesh(geometry, material);

// Add mesh to the scene
scene.add(mesh);

Panorama Environment Map#

// Create HDR loader
const hdrLoader = new RGBELoader()
// HDR loader has a callback function, which indicates that loading is complete and can be configured inside
const envMap = hdrLoader.load('/sandsloot_4k.hdr', (envMap) => {
  // Set the image to spherical mapping, panoramic images are used this way
  envMap.mapping = three.EquirectangularReflectionMapping
  // Set environment map
  scene.background = envMap
  // Set scene environment map
  scene.environment = envMap
  // Set cube material environment map
  material.envMap = envMap

})
const geometry = new three.PlaneGeometry(1, 1)
// Create geometry

const material = new three.MeshBasicMaterial({
  side: three.DoubleSide, // Double-sided
  color: 0xffffff, // Color
  map: texture, // Texture map
  transparent: true, // Transparent
  aoMap: aoTexture, // AO ambient occlusion map
  reflectivity: 0.2, // Reflection intensity
  alphaMap:alphaTexture, // Transparency map
  lightMap: lightMapTexture, // Light map
  specularMap: bumpMap, // Specular map
  aoMapIntensity: 0.5 // AO ambient occlusion intensity
})
const cube = new three.Mesh(geometry, material)
scene.add(cube)

Texture Switching to sRGB Color Space#

const texture = loader.load('/texture/watercover/CityNewYork002_COL_VAR1_1K.png')
// Default is linear color space, manually specify sRGB for better human perception
texture.colorSpace = three.SRGBColorSpace
  1. NoColorSpace - Default value, indicates no color space conversion.

  2. SRGBColorSpace - sRGB color space, suitable for display devices.

  3. LinearSRGBColorSpace - Linear sRGB color space, suitable for computer graphics.

Dynamically updating the color space requires calling the update function.

texture.needsUpdate = true

Fog#

  1. Linear Fog

  2. Exponential Fog

This article is synchronized by Mix Space to xLog
The original link is http://www.sroxck.top/posts/fontend/three


Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.