// 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);
three.js 和 OrbitControls。scene1 和 scene2。scene1 设置为当前场景。switchScene 函数,用于在两个场景之间进行渐隐渐现的切换效果。requestAnimationFrame 实现动画循环,不断更新控件并渲染当前场景。这个示例展示了如何使用 Three.js 实现场景之间的平滑切换效果。
上一篇:js 修改class
下一篇:js 页面加载
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站