threejs-textures

threejs-textures

熱門

Three.js 紋理 - 紋理類型、UV 映射、環境貼圖、紋理設定。適用於處理圖片、UV 座標、立方體貼圖、HDR 環境或紋理最佳化。

2633星標
301分支
更新於 2026/7/9
SKILL.md
唯讀
名稱
threejs-textures
描述

Three.js 紋理 - 紋理類型、UV 映射、環境貼圖、紋理設定。適用於處理圖片、UV 座標、立方體貼圖、HDR 環境或紋理最佳化。

Three.js 紋理

快速開始

import * as THREE from "three";

// 載入紋理
const loader = new THREE.TextureLoader();
const texture = loader.load("texture.jpg");

// 套用到材質
const material = new THREE.MeshStandardMaterial({
  map: texture,
});

紋理載入

基本載入

const loader = new THREE.TextureLoader();

// 非同步回呼
loader.load(
  "texture.jpg",
  (texture) => console.log("已載入"),
  (progress) => console.log("進度"),
  (error) => console.error("錯誤"),
);

// 同步風格(內部非同步載入)
const texture = loader.load("texture.jpg");
material.map = texture;

Promise 包裝

function loadTexture(url) {
  return new Promise((resolve, reject) => {
    new THREE.TextureLoader().load(url, resolve, undefined, reject);
  });
}

// 使用方式
const [colorMap, normalMap, roughnessMap] = await Promise.all([
  loadTexture("color.jpg"),
  loadTexture("normal.jpg"),
  loadTexture("roughness.jpg"),
]);

紋理設定

色彩空間

對準確色彩再現至關重要。

// 顏色/漫反射紋理 - 使用 sRGB
colorTexture.colorSpace = THREE.SRGBColorSpace;

// 資料紋理(法線、粗糙度、金屬度、AO)- 保持預設
// 不要對資料紋理設定 colorSpace(預設為 NoColorSpace)

包覆模式

texture.wrapS = THREE.RepeatWrapping; // 水平
texture.wrapT = THREE.RepeatWrapping; // 垂直

// 選項:
// THREE.ClampToEdgeWrapping - 拉伸邊緣像素(預設)
// THREE.RepeatWrapping - 平鋪紋理
// THREE.MirroredRepeatWrapping - 鏡像翻轉平鋪

重複、偏移、旋轉

// 平鋪紋理 4x4
texture.repeat.set(4, 4);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;

// 偏移(0-1 範圍)
texture.offset.set(0.5, 0.5);

// 旋轉(弧度,繞中心)
texture.rotation = Math.PI / 4;
texture.center.set(0.5, 0.5); // 旋轉軸心

濾波

// 縮小濾波(紋理大於螢幕像素)
texture.minFilter = THREE.LinearMipmapLinearFilter; // 預設,平滑
texture.minFilter = THREE.NearestFilter; // 像素化
texture.minFilter = THREE.LinearFilter; // 平滑,無 mipmap

// 放大濾波(紋理小於螢幕像素)
texture.magFilter = THREE.LinearFilter; // 平滑(預設)
texture.magFilter = THREE.NearestFilter; // 像素化(復古遊戲)

// 各向異性濾波(傾斜角度更清晰)
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();

產生 Mipmap

// 通常預設為 true
texture.generateMipmaps = true;

// 對非 2 的冪次紋理或資料紋理停用
texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter;

紋理類型

一般紋理

const texture = new THREE.Texture(image);
texture.needsUpdate = true;

資料紋理

從原始資料建立紋理。

// 建立漸層紋理
const size = 256;
const data = new Uint8Array(size * size * 4);

for (let i = 0; i < size; i++) {
  for (let j = 0; j < size; j++) {
    const index = (i * size + j) * 4;
    data[index] = i; // R
    data[index + 1] = j; // G
    data[index + 2] = 128; // B
    data[index + 3] = 255; // A
  }
}

const texture = new THREE.DataTexture(data, size, size);
texture.needsUpdate = true;

Canvas 紋理

const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext("2d");

// 在 canvas 上繪圖
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 256, 256);
ctx.fillStyle = "white";
ctx.font = "48px Arial";
ctx.fillText("Hello", 50, 150);

const texture = new THREE.CanvasTexture(canvas);

// 當 canvas 變更時更新
texture.needsUpdate = true;

影片紋理

const video = document.createElement("video");
video.src = "video.mp4";
video.loop = true;
video.muted = true;
video.play();

const texture = new THREE.VideoTexture(video);
texture.colorSpace = THREE.SRGBColorSpace;

// 無需設定 needsUpdate - 自動更新

壓縮紋理

import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";

const ktx2Loader = new KTX2Loader();
ktx2Loader.setTranscoderPath("path/to/basis/");
ktx2Loader.detectSupport(renderer);

ktx2Loader.load("texture.ktx2", (texture) => {
  material.map = texture;
});

立方體紋理

用於環境貼圖和天空盒。

CubeTextureLoader

const loader = new THREE.CubeTextureLoader();
const cubeTexture = loader.load([
  "px.jpg",
  "nx.jpg", // +X, -X
  "py.jpg",
  "ny.jpg", // +Y, -Y
  "pz.jpg",
  "nz.jpg", // +Z, -Z
]);

// 作為背景
scene.background = cubeTexture;

// 作為環境貼圖
scene.environment = cubeTexture;
material.envMap = cubeTexture;

等距柱狀投影轉立方體貼圖

import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js";

const pmremGenerator = new THREE.PMREMGenerator(renderer);
pmremGenerator.compileEquirectangularShader();

new RGBELoader().load("environment.hdr", (texture) => {
  const envMap = pmremGenerator.fromEquirectangular(texture).texture;
  scene.environment = envMap;
  scene.background = envMap;

  texture.dispose();
  pmremGenerator.dispose();
});

HDR 紋理

RGBELoader

import { RGBELoader } from "three/examples/jsm/loaders/RGBELoader.js";

const loader = new RGBELoader();
loader.load("environment.hdr", (texture) => {
  texture.mapping = THREE.EquirectangularReflectionMapping;
  scene.environment = texture;
  scene.background = texture;
});

EXRLoader

import { EXRLoader } from "three/examples/jsm/loaders/EXRLoader.js";

const loader = new EXRLoader();
loader.load("environment.exr", (texture) => {
  texture.mapping = THREE.EquirectangularReflectionMapping;
  scene.environment = texture;
});

背景選項

scene.background = texture;
scene.backgroundBlurriness = 0.5; // 0-1,模糊背景
scene.backgroundIntensity = 1.0; // 亮度
scene.backgroundRotation.y = Math.PI; // 旋轉背景

渲染目標

將場景渲染到紋理以產生特效。

// 建立渲染目標
const renderTarget = new THREE.WebGLRenderTarget(512, 512, {
  minFilter: THREE.LinearFilter,
  magFilter: THREE.LinearFilter,
  format: THREE.RGBAFormat,
});

// 將場景渲染到目標
renderer.setRenderTarget(renderTarget);
renderer.render(scene, camera);
renderer.setRenderTarget(null); // 回到螢幕

// 作為紋理使用
material.map = renderTarget.texture;

深度紋理

const renderTarget = new THREE.WebGLRenderTarget(512, 512);
renderTarget.depthTexture = new THREE.DepthTexture(
  512,
  512,
  THREE.UnsignedShortType,
);

// 存取深度
const depthTexture = renderTarget.depthTexture;

多重取樣渲染目標

const renderTarget = new THREE.WebGLRenderTarget(512, 512, {
  samples: 4, // MSAA
});

CubeCamera

用於反射的動態環境貼圖。

const cubeRenderTarget = new THREE.WebGLCubeRenderTarget(256, {
  generateMipmaps: true,
  minFilter: THREE.LinearMipmapLinearFilter,
});

const cubeCamera = new THREE.CubeCamera(0.1, 1000, cubeRenderTarget);
scene.add(cubeCamera);

// 套用到反射材質
reflectiveMaterial.envMap = cubeRenderTarget.texture;

// 在動畫迴圈中更新(耗效能!)
function animate() {
  // 隱藏反射物件,更新環境貼圖,再顯示
  reflectiveObject.visible = false;
  cubeCamera.position.copy(reflectiveObject.position);
  cubeCamera.update(renderer, scene);
  reflectiveObject.visible = true;
}

UV 映射

存取 UV

const uvs = geometry.attributes.uv;

// 讀取 UV
const u = uvs.getX(vertexIndex);
const v = uvs.getY(vertexIndex);

// 修改 UV
uvs.setXY(vertexIndex, newU, newV);
uvs.needsUpdate = true;

第二 UV 通道(用於 AO 貼圖)

// aoMap 需要 uv2
geometry.setAttribute("uv2", geometry.attributes.uv);

// 或建立自訂第二 UV
const uv2 = new Float32Array(vertexCount * 2);
// ... 填入 uv2 資料
geometry.setAttribute("uv2", new THREE.BufferAttribute(uv2, 2));

著色器中的 UV 變換

const material = new THREE.ShaderMaterial({
  uniforms: {
    map: { value: texture },
    uvOffset: { value: new THREE.Vector2(0, 0) },
    uvScale: { value: new THREE.Vector2(1, 1) },
  },
  vertexShader: `
    varying vec2 vUv;
    uniform vec2 uvOffset;
    uniform vec2 uvScale;

    void main() {
      vUv = uv * uvScale + uvOffset;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    varying vec2 vUv;
    uniform sampler2D map;

    void main() {
      gl_FragColor = texture2D(map, vUv);
    }
  `,
});

紋理圖集

將多張圖片合併到一個紋理中。

// 包含 4 個精靈的圖集(2x2 網格)
const atlas = loader.load("atlas.png");
atlas.wrapS = THREE.ClampToEdgeWrapping;
atlas.wrapT = THREE.ClampToEdgeWrapping;

// 透過 UV 偏移/縮放選擇精靈
function selectSprite(row, col, gridSize = 2) {
  atlas.offset.set(col / gridSize, 1 - (row + 1) / gridSize);
  atlas.repeat.set(1 / gridSize, 1 / gridSize);
}

// 選擇左上角精靈
selectSprite(0, 0);

材質紋理貼圖

PBR 紋理組合

const material = new THREE.MeshStandardMaterial({
  // 基本顏色(sRGB)
  map: colorTexture,

  // 表面細節(Linear)
  normalMap: normalTexture,
  normalScale: new THREE.Vector2(1, 1),

  // 粗糙度(Linear,灰階)
  roughnessMap: roughnessTexture,
  roughness: 1, // 倍率

  // 金屬度(Linear,灰階)
  metalnessMap: metalnessTexture,
  metalness: 1, // 倍率

  // 環境光遮蔽(Linear,使用 uv2)
  aoMap: aoTexture,
  aoMapIntensity: 1,

  // 自發光(sRGB)
  emissiveMap: emissiveTexture,
  emissive: 0xffffff,
  emissiveIntensity: 1,

  // 頂點位移(Linear)
  displacementMap: displacementTexture,
  displacementScale: 0.1,
  displacementBias: 0,

  // 透明度(Linear)
  alphaMap: alphaTexture,
  transparent: true,
});

// 別忘了 AO 需要 UV2
geometry.setAttribute("uv2", geometry.attributes.uv);

法線貼圖類型

// OpenGL 風格法線(預設)
material.normalMapType = THREE.TangentSpaceNormalMap;

// 物件空間法線
material.normalMapType = THREE.ObjectSpaceNormalMap;

程式化紋理

雜訊紋理

function generateNoiseTexture(size = 256) {
  const data = new Uint8Array(size * size * 4);

  for (let i = 0; i < size * size; i++) {
    const value = Math.random() * 255;
    data[i * 4] = value;
    data[i * 4 + 1] = value;
    data[i * 4 + 2] = value;
    data[i * 4 + 3] = 255;
  }

  const texture = new THREE.DataTexture(data, size, size);
  texture.needsUpdate = true;
  return texture;
}

漸層紋理

function generateGradientTexture(color1, color2, size = 256) {
  const canvas = document.createElement("canvas");
  canvas.width = size;
  canvas.height = 1;
  const ctx = canvas.getContext("2d");

  const gradient = ctx.createLinearGradient(0, 0, size, 0);
  gradient.addColorStop(0, color1);
  gradient.addColorStop(1, color2);

  ctx.fillStyle = gradient;
  ctx.fillRect(0, 0, size, 1);

  return new THREE.CanvasTexture(canvas);
}

紋理記憶體管理

釋放紋理

// 單一紋理
texture.dispose();

// 材質紋理
function disposeMaterial(material) {
  const maps = [
    "map",
    "normalMap",
    "roughnessMap",
    "metalnessMap",
    "aoMap",
    "emissiveMap",
    "displacementMap",
    "alphaMap",
    "envMap",
    "lightMap",
    "bumpMap",
    "specularMap",
  ];

  maps.forEach((mapName) => {
    if (material[mapName]) {
      material[mapName].dispose();
    }
  });

  material.dispose();
}

紋理池

class TexturePool {
  constructor() {
    this.textures = new Map();
    this.loader = new THREE.TextureLoader();
  }

  async get(url) {
    if (this.textures.has(url)) {
      return this.textures.get(url);
    }

    const texture = await new Promise((resolve, reject) => {
      this.loader.load(url, resolve, undefined, reject);
    });

    this.textures.set(url, texture);
    return texture;
  }

  dispose(url) {
    const texture = this.textures.get(url);
    if (texture) {
      texture.dispose();
      this.textures.delete(url);
    }
  }

  disposeAll() {
    this.textures.forEach((t) => t.dispose());
    this.textures.clear();
  }
}

效能提示

  1. 使用 2 的冪次尺寸:256、512、1024、2048
  2. 壓縮紋理:使用 KTX2/Basis 進行網路傳輸
  3. 使用紋理圖集:減少紋理切換
  4. 啟用 mipmap:用於遠距離物件
  5. 限制紋理大小:2048 通常足夠網頁使用
  6. 重複使用紋理:相同紋理可提升批次處理
// 檢查紋理記憶體
console.log(renderer.info.memory.textures);

// 針對行動裝置最佳化
const maxSize = renderer.capabilities.maxTextureSize;
const isMobile = /iPhone|iPad|Android/i.test(navigator.userAgent);
const textureSize = isMobile ? 1024 : 2048;

另請參閱

  • threejs-materials - 將紋理套用到材質
  • threejs-loaders - 載入紋理檔案
  • threejs-shaders - 自訂紋理取樣