效果
创建画布容器元素
< script setup lang = " ts" >
...
const canvasRef = ref< HTMLElement> ( )
const canvasSize = ref< { width : number, height : number } > ( { width : 0 , height : 0 } )
function handleResize ( entry : ResizeObserverEntry) {
canvasSize. value = { width : entry. contentRect. width, height : entry. contentRect. height}
}
...
</ script>
< template>
< div ref = " canvasRef" v-psr-resize-observer = " handleResize" />
</ template>
const renderer = new THREE . WebGLRenderer ( ) ;
const camera = new THREE . PerspectiveCamera (
75 ,
1 ,
0.1 ,
1000 ,
) ;
camera. position. z = 5 ;
const scene = new THREE . Scene ( ) ;
watch ( canvasRef, canvas => {
if ( canvas) {
canvas. appendChild ( renderer. domElement) ;
animate ( )
}
} )
function animate ( ) {
requestAnimationFrame ( animate) ;
renderer. render ( scene, camera) ;
}
watch ( canvasSize, canvasSize => {
renderer. setSize ( canvasSize. width, canvasSize. height, false ) ;
camera. aspect = canvasSize. width != 0 ? ( canvasSize. width / canvasSize. height) : 1
camera. updateProjectionMatrix ( )
} )
添加模型和动画
const geometry = new THREE . BoxGeometry ( 1 , 1 , 1 ) ;
const material = new THREE . MeshBasicMaterial ( { color: 0x00ff00 } ) ;
const cube = new THREE . Mesh ( geometry, material) ;
scene. add ( cube) ;
const aniInterval = setInterval ( ( ) => {
cube. rotation. x += 0.01
cube. rotation. y += 0.01
} , 1000 / 100 )
onUnmounted ( ( ) => {
clearInterval ( aniInterval)
} )