vue3中使用three.js
时间: 2023-11-25 09:06:58 浏览: 118
在Vue 3中使用three.js,可以按照以下步骤操作:
1. 安装three.js和@types/three:
```
npm install three @types/three
```
2. 在Vue组件中引入three.js:
```javascript
import * as THREE from 'three';
```
3. 在Vue组件中创建一个渲染器、相机、场景和一个立方体:
```javascript
export default {
mounted() {
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
},
};
```
4. 在Vue组件中渲染three.js画面:
```html
<template>
<div>
<canvas></canvas>
</div>
</template>
<script>
import * as THREE from 'three';
export default {
mounted() {
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
const animate = function () {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
},
};
</script>
<style>
canvas {
width: 100%;
height: 100%;
}
</style>
```
以上是一个简单的使用three.js的示例,你可以根据你的需求对其进行修改和扩展。
阅读全文