vue3 ts 写three.js
时间: 2023-05-23 19:02:26 浏览: 110
代码示例:
```typescript
import * as THREE from 'three';
import { createApp, defineComponent, onMounted, ref, Ref } from 'vue';
export default defineComponent({
setup() {
const canvasRef: Ref<HTMLCanvasElement | null> = ref(null);
let scene: THREE.Scene, camera: THREE.PerspectiveCamera, renderer: THREE.WebGLRenderer, cube: THREE.Mesh;
onMounted(() => {
if (canvasRef.value) {
const canvas = canvasRef.value;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
// create scene
scene = new THREE.Scene();
// create camera
camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.z = 3;
// create cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// create renderer
renderer = new THREE.WebGLRenderer({ canvas });
renderer.setSize(width, height);
// animate
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
}
});
return {
canvasRef,
};
},
template: '<canvas ref="canvasRef" />',
});
```
这是一个使用 Vue3 和 TypeScript 写的 three.js 的示例。它创建了一个场景、相机和一个立方体,并使用 WebGL 渲染器在画布上渲染出来,其中使用了 Vue3 中的 setup() 钩子函数来初始化场景,相机和立方体,并在 mounted 阶段初始化渲染器,并在动画帧中更新立方体的旋转,并再次渲染场景。
阅读全文