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 id="renderCanvas" touch-action="none"></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();
        });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章