出于对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 (
);
}
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", ,,, 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(, , ), scene);
// Create a built-in "sphere" shape; its constructor takes 6 params: name, segment, diameter, scene, updatable, sideOrientation
var sphere = BABYLON.Mesh.CreateSphere('sphere1', , , scene, false, BABYLON.Mesh.FRONTSIDE);
// Move the sphere upward 1/2 of its height
sphere.position.y = ;
// Create a built-in "ground" shape; its constructor takes 6 params : name, width, height, subdivision, scene, updatable
var ground = BABYLON.Mesh.CreateGround('ground1', , , , 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文档
手机扫一扫
移动阅读更方便
你可能感兴趣的文章