<template>
<div>
<div class="controls">
<label for="brightness">背景光亮度:</label>
<input
type="range"
id="brightness"
v-model="brightness"
min="0"
max="2"
step="0.1"
/>
<span>{{ brightness }}</span>
</div>
<div ref="container" className="three-container"></div>
</div>
</template>
<script setup>
import {ref, onMounted, onBeforeUnmount, watch} from 'vue';
import * as THREE from 'three';
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
const container = ref(null);
let scene, camera, renderer, controls, model;
let ambientLight;
const brightness = ref(1);
const initThree = () => {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffc0cb);
camera = new THREE.PerspectiveCamera(
75,
container.value.clientWidth / container.value.clientHeight,
0.1,
1000
);
camera.position.set(5, 5, 5);
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(container.value.clientWidth, container.value.clientHeight);
container.value.appendChild(renderer.domElement);
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
const ambientLight = new THREE.AmbientLight(0xffffff, brightness.value);
scene.add(ambientLight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.5;
const directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
};
const loadModel = () => {
const loader = new GLTFLoader();
loader.load(
'/api/demo.glb',
(gltf) => {
model = gltf.scene;
scene.add(model);
},
undefined,
(error) => {
console.error('An error happened while loading the model:', error);
}
);
};
const animate = () => {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
};
watch(brightness, (newBrightness) => {
if (ambientLight) {
ambientLight.intensity = newBrightness;
}
});
onMounted(() => {
initThree();
loadModel();
animate();
});
onBeforeUnmount(() => {
if (renderer) {
renderer.dispose();
}
});
</script>
<style scoped>
.three-container {
width: 100%;
height: 100vh;
}
</style>