webgl學習-babylon環境搭建

webgl學習-babylon環境搭建

從今天開始我們就進入對babylon的實踐環節,在這裡你估計學不到任何webgl和3d的基礎知識(因為我也不會),但是你可以學到一些基礎實踐示例,免去你去官網查詢的實踐。(吐槽一下,官網的文檔真的不會很友好,中文不全不說,示例也比較少,有時候查找某些東西隱藏的很深或者乾脆需要你自己試驗)

接下來我們進入學習babylon的第一步,搭建環境(額外聲明:本次所有代碼都是基於vue+webpack的,如果想看原生的小夥伴就不用往下看了)

首先,我們需要用npm下載所需要的包:

npm install 'babylonjs' //babylon的主體文件

npm install 'babylonjs-loaders' //模型加載文件,如果用不到加載外部模型,可以不用下載

接著,在需要的文件加載babylon:

 import * as BABYLON from 'babylonjs';

import 'babylonjs-loaders';

完成,這兩步就可以開始代碼的編寫工作了,這裡我們以一個官方示例為結束:

<canvas>

//拿到畫布


var canvas = document.getElementById("renderCanvas"); // Get the canvas element

var engine = new BABYLON.Engine(canvas, true); // Generate the BABYLON 3D engine

/******* Add the create scene function 創建場景 ******/

var createScene = function () {



// Create the scene space

var scene = new BABYLON.Scene(engine);



// Add a camera to the scene and attach it to the canvas

var camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2, 2, new BABYLON.Vector3(0,0,5), scene);

camera.attachControl(canvas, true);



// Add lights to the scene

var light1 = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(1, 1, 0), scene);

var light2 = new BABYLON.PointLight("light2", new BABYLON.Vector3(0, 1, -1), scene);



// Add and manipulate meshes in the scene

var sphere = BABYLON.MeshBuilder.CreateSphere("sphere", {diameter:2}, scene);



return scene;

};

/******* End of the create scene function ******/



var scene = createScene(); //Call the createScene function



// Register a render loop to repeatedly render the scene

engine.runRenderLoop(function () {

scene.render();

});



// Watch for browser/canvas resize events

window.addEventListener("resize", function () {

engine.resize();

});


分享到:


相關文章: