以下是一个使用Vue和Three.js创建的3D立方体的简单示例:
首先,你需要在你的Vue项目中安装Three.js。你可以通过npm或者yarn进行安装:
bash复制代码
npm install three --save | |
或者
bash复制代码
yarn add three | |
然后,你可以在你的Vue组件中使用Three.js。以下是一个示例Vue组件,它创建一个旋转的3D立方体:
vue复制代码
<template> | |
<div ref="threeContainer" class="three-container"></div> | |
</template> | |
<script> | |
import * as THREE from 'three'; | |
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; | |
import { onMounted, reactive, toRefs } from 'vue'; | |
export default { | |
setup() { | |
const state = reactive({ | |
scene: null, | |
camera: null, | |
renderer: null, | |
cube: null, | |
controls: null, | |
}); | |
onMounted(() => { | |
init(); | |
animate(); | |
}); | |
function init() { | |
const container = ElementById('threeContainer'); | |
state.scene = new THREE.Scene(); | |
state.camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000); | |
derer = new THREE.WebGLRenderer(); | |
derer.setSize(container.clientWidth, container.clientHeight); | |
container.derer.domElement); | |
ls = new OrbitControls(state.camera, derer.domElement); | |
const geometry = new THREE.BoxGeometry(1, 1, 1); | animate下载安装|
const material = new THREE.MeshBasicMaterial({ color: '#433F81' }); | |
state.cube = new THREE.Mesh(geometry, material); | |
state.scene.add(state.cube); | |
state.camera.position.z = 5; | |
} | |
function animate() { | |
requestAnimationFrame(animate); | |
ation.x += 0.01; | |
ation.y += 0.01; | |
der(state.scene, state.camera); | |
} | |
return { ...toRefs(state) }; | |
}, | |
}; | |
</script> | |
<style scoped> | |
.three-container { | |
width: 100%; | |
height: 100vh; | |
background-color: #000; | |
} | |
</style> | |
在这个示例中,我们首先在模板中创建一个div元素作为Three.js的容器。然后,在脚本部分,我们导入需要的模块,并设置一个响应式状态对象来存储我们的场景、相机、渲染器、立方体和控制器。我们在onMounted钩子函数中调用init函数来初始化Three.js场景,然后调用animate函数来开始动画循环。init函数创建一个新的场景、相机和渲染器,并将渲染器的dom元素添加到我们的容器中。然后,它创建一个新的立方体,并将其添加到场景中。最后,它将相机的位置设置为z轴上的5个单位。animate函数在每个动画帧上被调用,它更新立方体的旋转,并使用渲染器将场景渲染到屏幕上。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论