Cesium中插入html元素
Cesium中无法直接将dom节点直接渲染到Canvas界面中,需要调整下,可使用绝对定位的方式使dom节点脱离文档流并监听获取场景渲染后动态改变top或者left值达到插入html到场景效果,具体操作步骤如下:
- 构建dom节点
- 监听场景渲染
- 动态改变top\left
构建dom
以下以Vue为例创建box.vue文件
<div class="content">
测试html弹窗
</div>
<style scoped>
.content {
position: absolute; /* 重点 */
width: 200px;
line-height: 30px;
background-color: rgba(0, 0, 0, 0.8);
color: #fff;
padding: 8px 16px;
height: 100px;
}
</style>
监听场景渲染
import Vue from 'vue'
export default class PopupWindow {
constructor(viewer, position, domVue) {
let WindowVm = Vue.extend(domVue)
// 在此获取dom之后可进行数据操作,如传值等
this.vmInstance = new WindowVm().$mount()
this.viewer = viewer
this.position = position
// 将el节点挂载container
viewer.cesiumWidget.container.appendChild(this.vmInstance.$el)
this.addPostRender(position)
}
addPostRender() {
this.viewer.scene.postRender.addEventListener(this.postRender, this)
}
//场景渲染事件 实时更新标签的位置 使其与笛卡尔坐标一致
postRender() {
if (!this.vmInstance.$el || !this.vmInstance.$el.style) return
const canvasHeight = this.viewer.scene.canvas.height
const windowPosition = new window.Cesium.Cartesian2()
window.Cesium.SceneTransforms.wgs84ToWindowCoordinates(
this.viewer.scene,
this.position,
windowPosition
)
this.vmInstance.$el.style.bottom = canvasHeight - windowPosition.y + 'px'
this.vmInstance.$el.style.left = windowPosition.x + 'px'
if (!(this.viewer.camera.positionCartographic.height)) {
this.vmInstance.$el.style.display = 'none'
} else {
this.vmInstance.$el.style.display = 'block'
}
}
windowClose() {
this.vmInstance.show = false //删除dom
this.viewer.scene.postRender.removeEventListener(this.postRender, this) //移除事件监听
}
}