1. 创建一个Vue3项目
npm create vue@latest
2. 项目中安装three.js
npm install --save three
3. 找到你想要展示的页面,书写以下代码:
<template>
<div id="my-three"></div>
</template>
<script setup>
import * as THREE from "three"
import { onMounted } from "vue"
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
//创建一个三维场景
const scene = new THREE.Scene()
const geometry = new THREE.ConeGeometry(50, 100, 32)
const material = new THREE.MeshToonMaterial({
color: 0x008855,
})
const capsule = new THREE.Mesh(geometry, material)
scene.add(capsule)
// 创建一个相机【设置相机位置及相机方向】
const width = window.innerWidth
const height = window.innerHeight
const camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000)
camera.position.set(500, 200, 200)
camera.lookAt(0, 0, 0)
// 创建灯光
const light = new THREE.AmbientLight(0xffffff, 0.4) // 柔和的白光
scene.add(light)
const pointlight = new THREE.PointLight(0xffffff, 10, 100)
pointlight.position.set(50, 50, 50)
scene.add(pointlight)
// 创建渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(width, height)
renderer.render(scene, camera)
// 创建轨道控制器并开启监听【对控制器进行导入】
const controls = new OrbitControls(camera, renderer.domElement) //创建控件对象
controls.addEventListener("change", () => {
renderer.render(scene, camera) //监听鼠标,键盘事件
})
onMounted(() => {
document.getElementById("my-three")?.appendChild(renderer.domElement)
})
</script>
<style>
body {
margin: 0;
padding: 0;
}
</style>
4. 运行项目进入对应页面我们就能看见创建的几何体啦,动手试试吧!