一、在你的Vue项目中安装Three.js。你可以使用npm或yarn:
npm install three
二、创建一个Vue组件,用于在页面上显示Three.js场景。在组件中,你可以使用Vue的生命周期钩子方法来初始化Three.js场景,并在适当的时机更新它。
<template>
<div ref="canvas" />
</template>
<script>
import * as THREE from 'three';
export default {
mounted() {
this.initScene();
},
methods: {
initScene() {
// 创建场景
this.scene = new THREE.Scene();
// 创建相机
this.camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
this.camera.position.z = 5;
// 创建渲染器
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(window.innerWidth, window.innerHeight);
// 将渲染器的canvas添加到页面上
this.$refs.canvas.appendChild(this.renderer.domElement);
// 创建立方体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
this.cube = new THREE.Mesh(geometry, material);
// 将立方体添加到场景中
this.scene.add(this.cube);
// 开始渲染循环
this.animate();
},
animate() {
requestAnimationFrame(this.animate);
// 旋转立方体
this.cube.rotation.x += 0.01;
this.cube.rotation.y += 0.01;
// 渲染场景
this.renderer.render(this.scene, this.camera);
},
},
};
</script>
<style>
#canvas {
width: 100%;
height: 100vh;
}
</style>
三、将组件添加到你的页面中
<template>
<div>
<ThreeScene />
</div>
</template>
<script>
import ThreeScene from '@/components/ThreeScene.vue';
export default {
components: {
ThreeScene,
},
};
</script>
这个示例创建了一个简单的Three.js场景,在页面上旋转一个绿色的立方体。你可以根据自己的需求进行扩展和修改,使其更加丰富有趣!记得适配样式和动态缩放,这样就能保证在不同设备上正常显示。
灵感来源:ChartGPT