背景:
最近cesium交流群里看到好几个人都在问偏移问题。回答过几次 ,所以写个水文。到时候估计大家上网一搜就能搜到这篇。
在做popup弹窗的时候。思想是:需要将Cartesian3坐标转换为屏幕坐标 然后设置给div。就可以实现pop跟随。但是如果没有设置C3的高程 直接进行转换屏幕坐标 就会出现偏移。
解决办法:
将要转换的Cartesian3加上高程后 再进行转换屏幕坐标 就可以了
示例代码:
var viewer = new Cesium.Viewer("cesiumContainer");
// To geographically place an HTML element on top of the Cesium canvas, we use
// scene.cartesianToCanvasCoordinates to map a world position to canvas x and y values.
// This example places and img element, but any element will work.
var htmlOverlay = document.getElementById("htmlOverlay");
var scratch = new Cesium.Cartesian2();
viewer.scene.preRender.addEventListener(function () {
var position = Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883,这块高程参数加上就可以了);
var canvasPosition = viewer.scene.cartesianToCanvasCoordinates(
position,
scratch
);
if (Cesium.defined(canvasPosition)) {
htmlOverlay.style.top = canvasPosition.y + "px";
htmlOverlay.style.left = canvasPosition.x + "px";
}
});