<script setup lang="ts">
import * as THREE from 'three';
import {onMounted, ref} from "vue";
import { ArcballControls} from "three/examples/jsm/controls/ArcballControls";
const containerRef = ref(null)
const width = ref()
const height = ref()
const animateKey = ref(false)
let cube, camera, renderer,scene;
onMounted(() => {
width.value = containerRef.value.offsetWidth;
height.value = containerRef.value.offsetHeight;
initContainer()
})
const initContainer = () => {
scene = new THREE.Scene(); // 创建场景
camera = new THREE.PerspectiveCamera( 75, width.value / height.value, 0.1, 1000 );
// fov:视野角度, aspect:长宽比,near近截面,far:远截面
renderer = new THREE.WebGLRenderer();// 创建渲染器
renderer.setSize( width.value , height.value ); // 设置渲染器尺寸
containerRef.value.appendChild( renderer.domElement);
const geometry = new THREE.BoxGeometry( 50, 50, 10 ); // 模型
const material = new THREE.MeshBasicMaterial( { color: 0xff0033 } ); // 材质
cube = new THREE.Mesh( geometry, material ); // 网格 需包含模型和材质
// 控制器
const controls = new ArcballControls( camera, renderer.domElement, scene );
controls.addEventListener( 'change', function () {
renderer.render( scene, camera );
} );
scene.add( cube ); // 像场景中添加模型
camera.position.set( 0, 20, 100 );// 设置相机的位置
controls.update();// 控制器
animateKey.value = true
// 因为animate自启动时页面还没加完成,所以加了个变量,当animateKey为true时才执行animate内的方法
animate()
}
function animate() {
if(animateKey.value) {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
}
animate()
</script>
<template>
<div class="container" >
<div class="container_canvas" ref="containerRef"></div>
</div>
</template>
<style scoped lang="less">
.container {
width: 100%;
height: 100%;
box-sizing: border-box;
border: 1px solid red;
.container_canvas {
width: 80%;
height: 80%;
}
}
</style>