Babylon.js + Vue3 + TypeScript 环境搭建
一、技术栈选择
Vue3:前端框架,用于构建用户界面
TypeScript:类型化JavaScript,增强代码可维护性
Babylon.js:高性能3D引擎,支持WebGL渲染
二、项目初始化
# 创建Vue项目
npm create vue@latest
# 项目配置选择(建议)
✔ Project name: … my-babylon-app
✔ Add TypeScript? … Yes
✔ Add JSX Support? … No
✔ Add Vue Router? … No
✔ Add Pinia? … No
✔ Add Vitest? … No
✔ Add ESLint? … Yes
三、安装依赖
# 核心3D引擎
npm install @babylonjs/core
# 可选扩展
npm install @babylonjs/loaders # 模型加载器
npm install @babylonjs/gui # 2D界面组件
npm install @babylonjs/inspector # 调试工具
四、基础场景搭建
1.创建babylon文件
<!-- src/engine.ts-->
import { Engine, Scene, ArcRotateCamera, Vector3, HemisphericLight, MeshBuilder, Mesh } from '@babylonjs/core'
export class BabylonScene {
private engine: Engine
private scene: Scene
private sphere?: Mesh
constructor(private canvas: HTMLCanvasElement) {
this.engine = new Engine(this.canvas, true)
this.scene = new Scene(this.engine)
this.createScene()
this.startRenderLoop()
this.handleResize()
}
private createScene(): void {
// 创建相机
const camera = new ArcRotateCamera(
'arcCamera1',
-Math.PI / 2, // alpha: 水平旋转角度(-90度)
Math.PI / 3, // beta: 垂直旋转角度(60度)
10, // radius: 距离目标点的距离
new Vector3(0, 0, 0), // 目标点位置
this.scene
);
camera.attachControl(this.canvas)
//创建光源
const light = new HemisphericLight('light1', new Vector3(0, 1, 0), this.scene)
light.intensity = 0.7
// 创建球体
this.sphere = MeshBuilder.CreateSphere('sphere1', { diameter: 2 }, this.scene)
this.sphere.position.y = 1
}
private startRenderLoop(): void {
// 注册并执行一个渲染循环。引擎可以有多个渲染函数
this.engine.runRenderLoop(() => {
// 渲染场景
this.scene.render()
})
}
private handleResize(): void {
window.addEventListener('resize', () => {
// 根据画布的大小调整视图的大小
this.engine.resize()
})
}
public dispose(): void {
// 释放资源
this.engine.dispose()
this.scene.dispose()
}
}
2. 创建组件
<!-- src/BabylonEntry.vue -->
<template>
<canvas ref="renderCanvas"></canvas>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { BabylonScene } from '../engine.ts'
const renderCanvas = ref<HTMLCanvasElement | null>(null)
let babylonScene: BabylonScene | null = null
onMounted(() => {
if (renderCanvas.value) {
babylonScene = new BabylonScene(renderCanvas.value)
}
})
// onUnmounted : 这是一个在组件被卸载(销毁)之前执行的钩子函数。当组件即将从 DOM 中移除时会触发。
onUnmounted(() => {
babylonScene?.dispose()
})
</script>
<style scoped>
canvas {
width: 100%;
height: 100vh;
touch-action: none;
}
</style>
3. 在页面中使用组件
<template>
<BabylonEntry />
</template>
<script setup lang="ts">
import BabylonEntry from './components/BabylonEntry.vue';
</script>
<style></style>
五、项目运行
npm run dev
这是一个Babylon项目的简单实例,一个Babylon项目中需要包含:
1.engine
2.scene
3.Camera
4.light
5.Mesh