安装three.js
npm install three
在main.ts中全局注册three.js
import { createApp } from 'vue';
import App from './App.vue';
import * as THREE from 'three';
const app = createApp(App);
app.config.globalProperties.$THREE = THREE;
app.mount('#app');
在项目中使用three.js创建第一个场景
<template>
<div ref="canvasContainer"></div>
</template>
<script>
export default {
mounted() {
const scene = new this.$THREE.Scene()
const camera = new this.$THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
1000
);
const renderer = new this.$THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
this.$refs.canvasContainer.appendChild(renderer.domElement);
const geometry = new this.$THREE.BoxGeometry();
const material = new this.$THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new this.$THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 10;
const animate = () => {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
},
};
</script>
实现效果