- 新建 vue 项目
1 | vue create babylonjs-vue-app |
- 安装 babylon.js
1 | yarn add @babylonjs/core |
- 在根组件 App.vue 测试,测试用例来源 迈出第一步-让babylon运行起来
注意:所有代码写在 mounted() 内,vue 示例挂载后,dom 元素渲染后才能获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | <template> <canvas id="renderCanvas"></canvas> </template> <script> import * as BABYLON from "@babylonjs/core/Legacy/legacy"; export default {<!-- --> data() {<!-- --> return {<!-- -->}; }, mounted() {<!-- --> var canvas = document.getElementById("renderCanvas"); // 得到canvas对象的引用 var engine = new BABYLON.Engine(canvas, true); // 初始化 BABYLON 3D engine /******* Add the create scene function ******/ var createScene = function () {<!-- --> // 创建一个场景scene var scene = new BABYLON.Scene(engine); // 添加一个相机,并绑定鼠标事件 var camera = new BABYLON.ArcRotateCamera( "Camera", Math.PI / 2, Math.PI / 2, 2, new BABYLON.Vector3(0, 0, 5), scene ); camera.attachControl(canvas, true); // 添加一组灯光到场景 // eslint-disable-next-line no-unused-vars var light1 = new BABYLON.HemisphericLight( "light1", new BABYLON.Vector3(1, 1, 0), scene ); // eslint-disable-next-line no-unused-vars var light2 = new BABYLON.PointLight( "light2", new BABYLON.Vector3(0, 1, -1), scene ); // 添加一个球体到场景中 // eslint-disable-next-line no-unused-vars var sphere = BABYLON.MeshBuilder.CreateSphere( "sphere", {<!-- --> diameter: 2 }, scene ); return scene; }; /******* End of the create scene function ******/ var scene = createScene(); //Call the createScene function // 最后一步调用engine的runRenderLoop方案,执行scene.render(),让我们的3d场景渲染起来 engine.runRenderLoop(function () {<!-- --> scene.render(); }); // 监听浏览器改变大小的事件,通过调用engine.resize()来自适应窗口大小 window.addEventListener("resize", function () {<!-- --> engine.resize(); }); }, }; </script> <style> html,body,#app {<!-- --> overflow: hidden; width: 100%; height: 100%; margin: 0; padding: 0; } #renderCanvas {<!-- --> width: 100%; height: 100%; touch-action: none; } </style> |