代码
import {BaiduMapConfig, BaiduVectorTileProvider, Engine, GaussianSplat} from '@baidumap/mapv-three';
BaiduMapConfig.ak = '您的密钥';
const container = document.getElementById('map');
const aspect = container.clientWidth / container.clientHeight;
const center = [116.404, 39.915, 0];
const engine = new Engine(container, {
map: {
projection: 'EPSG:3857',
center,
range: 90 / Math.min(1, aspect),
pitch: 65,
heading: 25,
provider: new BaiduVectorTileProvider({
displayOptions: {
building: false,
poi: false,
},
}),
},
rendering: {
sky: null,
enableAnimationLoop: true,
},
});
// 用 .splat 格式(每个 splat 32 字节)在内存中生成一段双螺旋,接入自有数据时改用 url。
const BYTES_PER_SPLAT = 32;
function createDemoSplatData(count = 1200) {
const buffer = new ArrayBuffer(count * BYTES_PER_SPLAT);
const view = new DataView(buffer);
let seed = 20260906;
const random = () => {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 0x100000000;
};
for (let i = 0; i < count; i++) {
const offset = i * BYTES_PER_SPLAT;
const strand = i % 2;
const progress = Math.floor(i / 2) / (count / 2 - 1);
const angle = progress * Math.PI * 10 + strand * Math.PI;
const jitter = () => (random() - 0.5) * 0.7;
const x = Math.cos(angle) * 11 + jitter();
const y = progress * 36 - 18 + jitter();
const z = Math.sin(angle) * 11 + jitter();
const scale = 0.38 + random() * 0.18;
view.setFloat32(offset, x, true);
view.setFloat32(offset + 4, y, true);
view.setFloat32(offset + 8, z, true);
view.setFloat32(offset + 12, scale * 2.2, true);
view.setFloat32(offset + 16, scale, true);
view.setFloat32(offset + 20, scale * 0.7, true);
view.setUint8(offset + 24, strand ? 255 : 45);
view.setUint8(offset + 25, strand ? 75 : 110 + Math.round(100 * progress));
view.setUint8(offset + 26, strand ? 80 + Math.round(120 * progress) : 255);
view.setUint8(offset + 27, 195);
const halfAngle = -angle * 0.5;
const encodeRotation = (value) => Math.max(0, Math.min(255, Math.round(value * 128 + 128)));
view.setUint8(offset + 28, encodeRotation(Math.cos(halfAngle)));
view.setUint8(offset + 29, 128);
view.setUint8(offset + 30, encodeRotation(Math.sin(halfAngle)));
view.setUint8(offset + 31, 128);
}
return buffer;
}
const splat = engine.add(
new GaussianSplat({
data: createDemoSplatData(),
format: 'splat',
point: center,
}),
);
const info = document.getElementById('info');
splat.addEventListener('loaded', () => {
info.textContent = splat.count + ' 个 splat';
});
splat.addEventListener('error', ({error}) => {
info.textContent = '加载失败:' + error.message;
});
const opacity = document.getElementById('opacity');
opacity.addEventListener('input', () => {
splat.opacity = opacity.valueAsNumber;
engine.requestRender();
});
用 GaussianSplat 在天安门广场上方加载一段 3D Gaussian Splatting 数据,数据为内存中生成的 .splat 双螺旋,可拖动滑块调整透明度。
预览