typescript
复制代码
// 初始化场景、相机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建深度材质
const depthMaterial = new THREE.MeshDepthMaterial({
// 基础配置
depthPacking: THREE.RGBADepthPacking,
// 贴图配置(按需添加)
map: new THREE.TextureLoader().load('textures/diffuse.jpg'), // 颜色贴图
alphaMap: new THREE.TextureLoader().load('textures/alpha.png'), // 透明度贴图
// 位移效果配置
displacementMap: new THREE.TextureLoader().load('textures/height.png'),
displacementScale: 0.5,
displacementBias: -0.25,
// 线框模式
wireframe: false
});
// 创建几何体并应用材质
const geometry = new THREE.TorusKnotGeometry(1, 0.4, 100, 16);
const mesh = new THREE.Mesh(geometry, depthMaterial);
scene.add(mesh);
// 添加参考网格和灯光
scene.add(new THREE.GridHelper(10, 10));
scene.add(new THREE.AmbientLight(0x404040));
// 相机位置
camera.position.z = 3;
// 动画循环
function animate() {
requestAnimationFrame(animate);
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
// 响应窗口变化
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});