返回

Three.js 的 19 个最佳 JS 示例让您的 Web 设计熠熠生辉

前端

Three.js 是一个用于创建 3D 图形和动画的强大工具。通过整合这个库,开发者可以轻松地在网页上实现复杂的三维图形展示。以下是使用 Three.js 创建生动视觉效果的19个示例,这些方法能够帮助提升 Web 设计的整体表现力。

1. 基础渲染

首先了解如何设置一个基本的 Three.js 环境并渲染一个简单的几何形状:

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 material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}
animate();

2. 添加光照

通过添加光源,可以为场景增加真实感:

const light = new THREE.PointLight(0xffffff, 1, 100);
light.position.set(5, 5, 5);
scene.add(light);

const ambientLight = new THREE.AmbientLight(0x404040); // soft white light
scene.add(ambientLight);

3. 实现交互

使用鼠标或触摸屏控制物体旋转:

let rotationSpeed = 0.02;
document.addEventListener('mousemove', function(event) {
    const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
    cube.rotation.y += mouseX * rotationSpeed;
});

4. 动画效果

创建动画需要使用 Three.js 的 THREE.AnimationMixer

const loader = new THREE.GLTFLoader();
loader.load('path/to/model.glb', function(gltf) {
    scene.add(gltf.scene);
    
    const mixer = new THREE.AnimationMixer(gltf.scene);
    const action = mixer.clipAction(gltf.animations[0]);
    action.play();

    function animate() {
        requestAnimationFrame(animate);
        
        if (mixer) mixer.update(clock.getDelta());
        renderer.render(scene, camera);
    }
});

5. 演示3D模型

Three.js 能够轻松加载并展示3D模型:

const loader = new THREE.GLTFLoader();
loader.load('path/to/model.glb', function(gltf) {
    scene.add(gltf.scene);
}, undefined, function(error) {
    console.error(error);
});

6. 阴影效果

启用阴影可以让场景看起来更加真实:

const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 5, 5).normalize();
scene.add(light);

cube.castShadow = true;
light.castShadow = true;

renderer.shadowMap.enabled = true;

7. 使用纹理

为物体添加纹理可以让它们看起来更加自然:

const textureLoader = new THREE.TextureLoader();
textureLoader.load('path/to/texture.jpg', function(texture) {
    const material = new THREE.MeshBasicMaterial({ map: texture });
    cube.material = material;
});

8. 使用相机控制

Three.js 提供了多种方式来操控相机视角:

const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update();

这些示例只是 Three.js 强大功能的冰山一角。开发者可以根据具体需求,结合以上技巧创造出更多独特且吸引人的视觉效果。

相关资源

通过深入探索这些示例和技术,Web 开发者可以轻松地在网站中添加丰富的 3D 内容。