本文解决在vue项目中使用mapbox和three.js渲染三维物体时,拖动地图视角导致物体底部偏移的问题。 目标是确保三维物体始终固定在指定的地图坐标位置。

问题描述:
三维物体成功渲染在Mapbox地图上,但拖动地图时,物体底部会发生偏移,不再保持在初始经纬度位置。
解决方案:
立即学习“前端免费学习笔记(深入)”;
核心在于同步Three.js场景矩阵和Mapbox视图矩阵。需要修正物体位置,使其与Mapbox的墨卡托投影坐标系匹配,并考虑视角变化对三维物体投影的影响。
代码调整:
以下代码片段展示了render函数和calculateModelTransform函数的修改:
1. 调整render函数:
使用mapboxgl.MercatorCoordinate设置物体位置,并考虑地图视角变化。
render: (gl, matrix) => {
console.log(`custom layer rendering: ${customlayer.id}`);
const m = new THREE.Matrix4().fromArray(matrix);
// 使用墨卡托坐标系的位置
const modelPosition = mapboxgl.MercatorCoordinate.fromLngLat([point.lng, point.lat], this.modelAltitude);
const l = new THREE.Matrix4().makeTranslation(modelPosition.x, modelPosition.y, modelPosition.z)
.scale(new THREE.Vector3(modelTransform.scale, -modelTransform.scale, modelTransform.scale)) // 注意Y轴缩放的负号
.multiply(new THREE.Matrix4().makeRotationFromEuler(new THREE.Euler(this.modelRotate[0], this.modelRotate[1], this.modelRotate[2])));
customLayer.camera.projectionMatrix = m.multiply(l);
customLayer.renderer.resetState();
customLayer.renderer.render(customLayer.scene, customLayer.camera);
customLayer.map.triggerRepaint();
}2. 调整calculateModelTransform函数:
translateZ参数设为0,确保物体底部固定在地图上。 同时,使用meterInMercatorCoordinateUnits()获取合适的缩放比例。
calculateModelTransform(point) {
const modelAsMercatorCoordinate = mapboxgl.MercatorCoordinate.fromLngLat([point.lng, point.lat], this.modelAltitude);
return {
translateX: modelAsMercatorCoordinate.x,
translateY: modelAsMercatorCoordinate.y,
translateZ: 0, // 物体底部固定
rotateX: this.modelRotate[0],
rotateY: this.modelRotate[1],
rotateZ: this.modelRotate[2],
scale: modelAsMercatorCoordinate.meterInMercatorCoordinateUnits() // 使用墨卡托单位下的米数进行缩放
};
}通过以上调整,三维物体底部将始终固定在预设的经纬度位置,无论地图视角如何变化。 请注意代码中THREE和mapboxgl的正确引用。 Y轴缩放的负号确保物体方向正确。 使用meterInMercatorCoordinateUnits()可以更准确地控制缩放比例,使其与地图比例一致。
以上就是在Vue中使用Mapbox和Three.js时,如何确保三维物体的坐标点与地图视角一致?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号