记录一下three.js配合vite+vue3的使用。
使用npm安装:
npm install --save three
<template>
<div ref="threeContainer" class="w-full h-full"></div>
</template>
可以给这个div
定义一个ref
,之后会使用ref
获取该页面的宽和高以及插入canvas
,或者直接插入document.body
。这里有一个前提,这个div
需要被定义确定的宽和高,例如style="width:100vw;height:100vh"
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
import { Water } from 'three/examples/jsm/objects/Water2.js';
import gsap from 'gsap';
let scene: any, camera: any, renderer: any, controls: any, dracoLoader: any, gltfLoader: any, starsInstance: any;
onUnmounted(() => {
// 退出时清理资源
if (renderer) renderer.dispose();
});
const initThree = () => {
// 初始化场景
scene = new THREE.Scene();
// 初始化相机
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(-3.23, 2.98, 4.06);
camera.updateProjectionMatrix();
// 初始化渲染器
renderer = new THREE.WebGLRenderer({
// 设置抗锯齿
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
// 渲染完成后插入body
document.body.appendChild(renderer.domElement);
// 设置色调映射
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 0.5;
renderer.shadowMap.enabled = true;
renderer.physicallyCorrectLights = true;
// 初始化控制器
controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(-8, 2, 0);
controls.enableDamping = true;
// 初始化loader以及设置压缩模型的解压缩地址
dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('./draco/');
gltfLoader = new GLTFLoader();
gltfLoader.setDRACOLoader(dracoLoader);
// 加载环境纹理,天空鱼眼图片
const rgbeLoader = new RGBELoader();
rgbeLoader.load('./textures/sky.hdr', (texture) => {
texture.mapping = THREE.EquirectangularReflectionMapping;
scene.background = texture;
scene.environment = texture;
});
// 加载模型
gltfLoader.load('./model/scene.glb', (gltf: any) => {
const model = gltf.scene;
model.traverse((child: any) => {
if (child.name === 'Plane') {
child.visible = false;
}
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
scene.add(model);
});
// 设置灯光
initLight();
};
const initLight = () => {
// 添加平行光
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 50, 0);
scene.add(light);
};
const render = () => {
requestAnimationFrame(render);
renderer.render(scene, camera);
controls.update();
};
initThree();
render();
// 监听鼠标事件
window.addEventListener(
'click',
(e) => {
if (isAnimate) return;
isAnimate = true;
index.value++;
if (index.value > scenes.length - 1) {
index.value = 0;
restoreHeart();
}
scenes[index.value].callback();
setTimeout(() => {
isAnimate = false;
}, 1000);
},
false
);