// 引入Three.js库
import * as THREE from 'three';
// 创建场景
const scene = new THREE.Scene();
// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建几何体
const geometry = new THREE.BoxGeometry();
// 基础纹理
const basicTexture = new THREE.TextureLoader().load('path/to/basic.jpg');
const basicMaterial = new THREE.MeshBasicMaterial({ map: basicTexture });
const basicCube = new THREE.Mesh(geometry, basicMaterial);
scene.add(basicCube);
// 凹凸纹理
const bumpTexture = new THREE.TextureLoader().load('path/to/bump.jpg');
const bumpMaterial = new THREE.MeshPhongMaterial({ map: basicTexture, bumpMap: bumpTexture, bumpScale: 1 });
const bumpCube = new THREE.Mesh(geometry, bumpMaterial);
scene.add(bumpCube);
// 法向贴图
const normalTexture = new THREE.TextureLoader().load('path/to/normal.jpg');
const normalMaterial = new THREE.MeshPhongMaterial({ normalMap: normalTexture });
const normalCube = new THREE.Mesh(geometry, normalMaterial);
scene.add(normalCube);
// 环境贴图
const envTexture = new THREE.TextureLoader().load('path/to/env.jpg');
const envMaterial = new THREE.MeshPhongMaterial({ envMap: envTexture });
const envCube = new THREE.Mesh(geometry, envMaterial);
scene.add(envCube);
// Canvas贴图
function generateCanvasTexture() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 128;
canvas.height = 128;
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 64, 64);
ctx.fillStyle = 'green';
ctx.fillRect(64, 0, 64, 64);
return new THREE.CanvasTexture(canvas);
}
const canvasTexture = generateCanvasTexture();
const canvasMaterial = new THREE.MeshPhongMaterial({ map: canvasTexture });
const canvasCube = new THREE.Mesh(geometry, canvasMaterial);
scene.add(canvasCube);
// 设置相机位置并开始渲染循环
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
这段代码展示了如何在Three.js中加载并应用不同类型的贴图。它首先创建了一个场景、相机和渲染器,然后定义了一个立方体几何体。接着,它演示了如何使用基本纹理、凹凸纹理、法向贴图、环境贴图和Canvas贴图。最后,它设置了相机位置并启动了渲染循环。