8 【CesiumJS入门】自定义鼠标指针图标——地球范围内实现

前言
要做一个鼠标打点的功能,那么对鼠标指针的样式就有了可变的需求 。效果如下图,当鼠标进入到地球范围内时,就修改自定义的样式 。离开地球后就恢复默认样式 。
示例指针图标来自 GIS产品彩色系功能图标库,十分感谢公开 。

8  【CesiumJS入门】自定义鼠标指针图标——地球范围内实现

文章插图
代码
/** @Date: 2023-07-30 21:16:14* @LastEditors: ReBeX420659880@qq.com* @LastEditTime: 2023-08-01 09:00:00* @FilePath: \cesium-tyro-blog\src\utils\Event\cursorEvent.js* @Description: 鼠标指针相关事件* import { pickCursor } from '@/utils/Event/cursorEvent.js'*/import { viewer } from '@/utils/createCesium.js' // 引入地图对象import * as Cesium from 'cesium'let handleInstance // 指针实例const svgIcon = ``const iconUrl = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgIcon)))function pickCursor(boolean = true) {if (!handleInstance) {handleInstance = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);}// ! 优化方向:减少DOM操作,将获取地球容器元素的操作放在函数外部,并将其作为参数传入函数,减少函数内部对DOM的多次查询 。const globeElement = document.getElementById("cesiumContainer"); // ! 替换为你的地球场景容器元素IDif (!boolean) {handleInstance.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);globeElement.style.cursor = "default"; // 恢复指针样式为默认值return}handleInstance.setInputAction(({ endPosition }) => {// 将鼠标位置从屏幕坐标系转换为世界坐标系const ray = viewer.camera.getPickRay(endPosition);const intersection = viewer.scene.globe.pick(ray, viewer.scene);if (Cesium.defined(intersection)) {// 鼠标在地球上globeElement.style.cursor = `url(${iconUrl}) 24 24,auto` // url后的两个 24 24目的是将图片的中心定位在光标的有效点(热点)// globeElement.style.cursor = 'pointer' // 参考:https://developer.mozilla.org/zh-CN/docs/Web/CSS/cursor} else {// 鼠标不在地球上globeElement.style.cursor = "default"; // 恢复指针样式为默认值}}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);}export {pickCursor}
调用方式:
【8【CesiumJS入门】自定义鼠标指针图标——地球范围内实现】!注意:需要将上述代码中的换成你自己用来挂载地球的dom元素id 。
import { pickCursor } from '@/utils/Event/cursorEvent.js'pickCursor (true) // 启用该功能pickCursor (false) // 关闭该功能