Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

threejs 场景切换动画

作者:╭ァ你不懂的悲殇   发布日期:2025-11-03   浏览:20

// threejs 场景切换动画示例代码

// 引入three.js库
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

// 创建场景
const scene1 = new THREE.Scene();
const scene2 = new THREE.Scene();

// 创建相机
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 添加控件
const controls = new OrbitControls(camera, renderer.domElement);

// 创建几何体和材质,并添加到场景1
const geometry1 = new THREE.BoxGeometry();
const material1 = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube1 = new THREE.Mesh(geometry1, material1);
scene1.add(cube1);

// 创建几何体和材质,并添加到场景2
const geometry2 = new THREE.SphereGeometry();
const material2 = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const sphere = new THREE.Mesh(geometry2, material2);
scene2.add(sphere);

// 定义当前场景
let currentScene = scene1;

// 切换场景的函数
function switchScene(newScene) {
    // 渐隐效果
    const transitionDuration = 1000; // 持续时间,单位为毫秒
    let alpha = 1;
    function fadeOut() {
        if (alpha > 0) {
            alpha -= 0.01;
            renderer.setClearColor(0x000000, alpha);
            requestAnimationFrame(fadeOut);
        } else {
            currentScene = newScene;
            fadeIn();
        }
    }

    function fadeIn() {
        if (alpha < 1) {
            alpha += 0.01;
            renderer.setClearColor(0x000000, alpha);
            requestAnimationFrame(fadeIn);
        }
    }

    fadeOut();
}

// 动画循环
function animate() {
    requestAnimationFrame(animate);

    // 更新控件
    controls.update();

    // 渲染当前场景
    renderer.render(currentScene, camera);
}

animate();

// 添加一个按钮来触发场景切换
const button = document.createElement('button');
button.innerText = '切换场景';
button.onclick = () => {
    if (currentScene === scene1) {
        switchScene(scene2);
    } else {
        switchScene(scene1);
    }
};
document.body.appendChild(button);

解释说明:

  1. 引入库:首先引入了 three.jsOrbitControls
  2. 创建场景:创建了两个不同的场景 scene1scene2
  3. 创建相机:创建了一个透视相机并设置其位置。
  4. 创建渲染器:创建了一个 WebGL 渲染器,并将其添加到页面中。
  5. 添加控件:添加了轨道控件以便可以自由旋转视角。
  6. 创建几何体和材质:分别为两个场景创建了不同的几何体(立方体和球体),并设置了材质。
  7. 定义当前场景:初始化时将 scene1 设置为当前场景。
  8. 切换场景的函数:定义了一个 switchScene 函数,用于在两个场景之间进行渐隐渐现的切换效果。
  9. 动画循环:通过 requestAnimationFrame 实现动画循环,不断更新控件并渲染当前场景。
  10. 添加按钮:添加了一个按钮,点击按钮时会触发场景切换。

这个示例展示了如何使用 Three.js 实现场景之间的平滑切换效果。

上一篇:js 修改class

下一篇:js 页面加载

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站