babylon 初試


出於對web端3D技術的對比,以及WebGL的發展現狀和WebGPU的發展前景,我覺得有必要涉獵一下babylon.js了。

可以參考一下下列文章:

1⃣️下一代web端圖形接口現狀與前景:https://zhuanlan.zhihu.com/p/59691803

今天就先在react里面測試一下官方demo:

demo的核心代碼如下:

import {MiddleComponent,React} from '../../../utils/MiddleComponent'
import * as BABYLON from 'babylonjs';


export class babylon1 extends MiddleComponent {
    constructor(props){
    super(props);
    }
    
  render() {
    return (
      <canvas id="renderCanvas" style={{width:'100%',height:'100%',position:'relative'}}></canvas>
    );
  }

  componentDidMount() {
    this.init();
  }
  
  init = ()=> {
    // Get the canvas DOM element
    var canvas = document.getElementById('renderCanvas');
    // Load the 3D engine
    var engine = new BABYLON.Engine(canvas, true, {preserveDrawingBuffer: true, stencil: true});
    // Create a basic BJS Scene object
    var scene = new BABYLON.Scene(engine);
    // Create a FreeCamera, and set its position to {x: 0, y: 5, z: -10}
    var camera = new BABYLON.ArcRotateCamera("Camera", 1,1,12, BABYLON.Vector3.Zero(), scene);
    // Target the camera to scene origin
    camera.setTarget(BABYLON.Vector3.Zero());
    // Attach the camera to the canvas
    camera.attachControl(canvas, false);
    // Create a basic light, aiming 0, 1, 0 - meaning, to the sky
    var light = new BABYLON.HemisphericLight('light1', new BABYLON.Vector3(0, 1, 0), scene);
    // Create a built-in "sphere" shape; its constructor takes 6 params: name, segment, diameter, scene, updatable, sideOrientation
    var sphere = BABYLON.Mesh.CreateSphere('sphere1', 16, 2, scene, false, BABYLON.Mesh.FRONTSIDE);
    // Move the sphere upward 1/2 of its height
    sphere.position.y = 1;
    // Create a built-in "ground" shape; its constructor takes 6 params : name, width, height, subdivision, scene, updatable
    var ground = BABYLON.Mesh.CreateGround('ground1', 6, 6, 2, scene, false);
    // run the render loop
    engine.runRenderLoop(function(){
        scene.render();
    });
    // the canvas/window resize event handler
    window.addEventListener('resize', function(){
        engine.resize();
    });
  }
}

  

如果你接觸過three.js的話,其實上述代碼並沒有什么值得講解的地方,並且你也會發現babylon.js和three.js還是有一些差異的。

如果沒有接觸過three.js或者其他webgl類庫或者引擎,那就先學習一下webgl相關知識吧。

注意:

MiddleComponent 是我自己封裝的組件,你可以選擇在你的react程序里繼承自Component。

點擊當前頁面右上角箭頭,有我自制的babylon相關api文檔





 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM