效果
创建画布容器元素
<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>
创建threejs渲染器,相机,场景
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()
})
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
添加模型和动画
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)
})