本文主要介紹如何使用Vue3和TypeScript引入BabylonJs技術(shù)實(shí)現(xiàn)3D效果。結(jié)合實(shí)際案例,詳細(xì)講解了如何在Vue3項(xiàng)目中引入BabylonJs,并了解其相關(guān)知識(shí)。通過(guò)本文的學(xué)習(xí),相信讀者可以輕松掌握Vue3實(shí)現(xiàn)3D效果以及BabylonJs的相關(guān)知識(shí)。
一、創(chuàng)建項(xiàng)目
1、創(chuàng)建Vue3 + TypeScript項(xiàng)目
npm create vite@latest babylonjs-vue3-ts -- --template vue
將生成的js文件都修改為ts文件
2、用WebStorm打開(kāi)項(xiàng)目
(1)打開(kāi)項(xiàng)目以后執(zhí)行 npm install
(2)運(yùn)行項(xiàng)目npm run dev
訪問(wèn):http://127.0.0.1:5173/
二、引入 BabylonJs
我們需要將Babylon包安裝到項(xiàng)目中,并使用其中的幾個(gè)包。我們從Babylon的核心包開(kāi)始,使用以下命令在終端中進(jìn)行安裝:
npm install @babylonjs/core
三、創(chuàng)建 Babylon.vue
<template>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
onMounted(()=>{
const canvas = document.querySelector("canvas")
})
</script>
<style scoped>
</style>
// @ts-ignore
import { Scene, Engine,FreeCamera,HemisphericLight,Vector3 ,MeshBuilder,MeshBuilder} from "@babylonjs/core"
export class BabylonScene {
scene: Scene;
engine: Engine;
constructor(private canvas: HTMLCanvasElement) {
this.engine = new Engine(this.canvas, true);
this.scene = this.CreateScene();
this.engine.runRenderLoop(() => {
this.scene.render();
});
}
CreateScene(): Scene {
const scene = new Scene(this.engine);
//創(chuàng)建和定位自由攝影機(jī)
const camera = new FreeCamera("camera1",
new Vector3(0, 5, -10), scene);
// 將攝影機(jī)定位到場(chǎng)景原點(diǎn)
camera.setTarget(Vector3.Zero());
// 這會(huì)將相機(jī)連接到畫(huà)布
camera.attachControl(this.canvas, true);
// 創(chuàng)建燈光,目標(biāo)為0,1,0-指向天空
const light = new HemisphericLight("light",
new Vector3(0, 1, 0), scene);
// 將燈光調(diào)暗一小部分-0到1
light.intensity = 0.7;
// 內(nèi)置“球體”形狀。
const sphere = MeshBuilder.CreateSphere("sphere",
{diameter: 2, segments: 32}, scene);
// 將球體向上移動(dòng)其高度的1/2
sphere.position.y = 1;
// 內(nèi)置“地面”形狀。
const ground = MeshBuilder.CreateGround("ground",
{width: 6, height: 6}, scene);
return scene;
}
}
四、場(chǎng)景渲染
在Babylon.vue引入剛剛創(chuàng)建的BabylonScene
<template>
<div >
<canvas style="height: 100%;width: 100%"></canvas>
</div>
</template>
<script setup lang="ts">
import { onMounted } from 'vue';
import { BabylonScene } from '../BabylonEngine/BabylonScene';
onMounted(()=>{
const canvas = document.querySelector("canvas");
var scene = new BabylonScene(canvas);
})
</script>
<style scoped>
</style>
在App.vue 引入Babylon.vue組件文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-441375.html
五、運(yùn)行最終效果
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-441375.html
到了這里,關(guān)于Vue3 +TypeScript 引入 BabylonJs(Vue3實(shí)現(xiàn)3D)【一篇文章精通系列】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!