1.引入相关依赖,构建mapbox地图场景
import mapboxgl from 'mapbox-gl';
import {onMounted} from "vue";
import * as BABYLON from 'babylonjs';
mapboxgl.accessToken = 'pk.eyJ1Ijoibm9haDk3MTMiLCJhIjoiY2p4aXppNXZoMTc4YTN5bzhzMWY0emw3cyJ9.7GhaVOSALR-DwV5Lpn_h4Q';
const map = new mapboxgl.Map({
container: 'mapContainer',
style: 'mapbox://styles/mapbox/streets-v11',
zoom: 18,
center: [120, 31],
pitch: 60,
antialias: true // create the gl context with MSAA antialiasing, so custom layers are antialiased
});
2.根据CustomLayerInterface定义一个BabylonLayer
class BabylonLayer implements CustomLayerInterface {
readonly id: string;
readonly type: 'custom' = 'custom';
readonly renderingMode: '3d' = '3d';
private map: Map | undefined;
private scene: BABYLON.Scene | undefined;
private camera: BABYLON.Camera | undefined;
constructor(id: string) {
this.id = id;
}
onAdd = (map: Map, gl: WebGLRenderingContext) => {
this.map = map;
const engine = new BABYLON.Engine(gl, true, {
useHighPrecisionMatrix: true
}, true);
this.scene = new BABYLON.Scene(engine);
this.scene.autoClear = false;
this.scene.detachControl();
this.scene.beforeRender = function(){
engine.wipeCaches(true);
};
this.camera = new BABYLON.Camera("mapbox-camera", new BABYLON.Vector3(), this.scene);
const light = new BABYLON.HemisphericLight("mapbox-light", new BABYLON.Vector3(0.5, 0.5, 4000), this.scene);
// 创建正方体
const boxCoord = mapboxgl.MercatorCoordinate.fromLngLat([120, 31], 200);
const boxMesh = BABYLON.MeshBuilder.CreateBox('box', {
size: 200 * boxCoord.meterInMercatorCoordinateUnits()
}, this.scene);
boxMesh.position = new BABYLON.Vector3(boxCoord.x, boxCoord.y, boxCoord.z);
// 创建球
const sphereCoord = mapboxgl.MercatorCoordinate.fromLngLat([120.01, 31], 200);
const sphereMesh = BABYLON.MeshBuilder.CreateSphere('sphere', {
diameter: 300 * sphereCoord.meterInMercatorCoordinateUnits()
}, this.scene);
sphereMesh.position = new BABYLON.Vector3(sphereCoord.x, sphereCoord.y, sphereCoord.z);
}
render = (gl: WebGLRenderingContext, matrix: number[]) => {
const cameraMatrix = BABYLON.Matrix.FromArray(matrix);
this.camera!.freezeProjectionMatrix(cameraMatrix);
this.scene!.render(false);
this.map!.triggerRepaint();
}
}
3.添加BabylonLayer至mapbox场景
map.on('style.load', () => {
const babylonLayer = new BabylonLayer('babylon-layer');
map.addLayer(babylonLayer);
});
实现效果:

文章介绍了如何在Mapbox地图场景中引入Babylon.js库,创建并实现一个自定义3D渲染层,展示了如何添加立方体和球体模型并进行渲染。

142

被折叠的 条评论
为什么被折叠?



