返回 导航

Vue.js

hangge.com

Vue.js - 集成Cesium构建三维可视化场景教程7(实体鼠标悬停高亮、点击选中效果)

作者:hangge | 2026-07-10 08:46
      在之前文章中我们已经成功搭建了三维底图并加载了各种实体(Entity)。但一个只能看不能动的场景就像一张精美的壁纸,少了点“灵魂”。本文我们让场景对象的交互动起来,具体包括实现实体的鼠标悬停高亮(Hover) 和点击选中(Select) 效果。

七、实现实体鼠标悬停高亮、点击选中效果

1,样例代码

    下面样例对多种实体进行统一的鼠标悬浮高亮和选中效果。当鼠标悬停或点击实体时,模型通过 silhouette 描边、多边形通过 outline 边框高亮,点与 Billboard 则通过动态生成的光圈辅助实体进行强调显示,同时在状态切换时自动恢复原始样式。
<template>
    <div class="layer-container">
        <div ref="cesiumContainer" class="cesium-container"></div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-spinner"></div>
            <p>加载三维场景中...</p>
        </div>
    </div>
</template>

<script>
// 引入 Cesium 核心类
import * as Cesium from "cesium";

export default {
    name: 'CesiumViewer',

    data() {
        return {
            viewer: null,
            loading: true,
            terrainEnabled: true,
            sampleEntities: [],
            // 鼠标事件句柄
            handler: null,
            // 悬停状态
            hovered: {
                entity: null,
                originalStyle: null
            },
            // 选中状态
            selected: {
                entity: null,
                originalStyle: null
            },
            // 悬浮/选中光圈
            outlineAssist: {
                hoverEllipse: null,
                selectEllipse: null
            }
        }
    },

    mounted() {
        // 确保 Cesium 已加载
        if (typeof Cesium === 'undefined') {
            console.error('Cesium 未加载,请检查配置')
            this.loading = false
            return
        }

        // 初始化 Cesium 场景
        this.initCesium()
    },

    beforeDestroy() {
        // 组件销毁时清理资源
        this.destroyCesium()
    },

    methods: {
        // 初始化 Cesium
        async initCesium() {
            try {
                // 配置 Cesium 访问令牌(如果需要,从 Cesium Ion 获取)
                //Cesium.Ion.defaultAccessToken = '你的Cesium Ion访问令牌'

                // 创建 Viewer 实例
                this.viewer = new Cesium.Viewer(this.$refs.cesiumContainer, {
                    animation: false, // 是否显示动画控件
                    baseLayerPicker: false, // 是否显示图层选择控件
                    fullscreenButton: false, // 是否显示全屏按钮
                    geocoder: false, // 是否显示地理编码搜索控件
                    homeButton: false, // 是否显示Home按钮
                    infoBox: false, // 是否显示信息框
                    sceneModePicker: false, // 是否显示3D/2D选择器
                    selectionIndicator: false, // 是否显示选取指示器组件
                    timeline: false, // 是否显示时间轴
                    navigationHelpButton: false, // 是否显示帮助按钮
                    scene3DOnly: true, // 每个几何实例仅以3D渲染以节省GPU内存
                    shouldAnimate: true, // 自动播放动画
                    // 地形配置
                    terrainProvider: await Cesium.createWorldTerrainAsync()
                })

                // 强制重新计算画布尺寸
                this.viewer.canvas.width = this.viewer.container.clientWidth;
                this.viewer.canvas.height = this.viewer.container.clientHeight;
                this.viewer.resize(); // 核心方法:告知 Cesium 容器大小已变

                // 设置初始视图
                this.setInitialView()

                // 添加示例实体
                this.addDemoEntities()

                // 鼠标事件初始化
                this.initPickEvents()

                // 加载完成
                this.loading = false

                console.log('Cesium 场景初始化完成')
            } catch (error) {
                console.error('初始化 Cesium 失败:', error)
                this.loading = false
            }
        },

        // 设置初始视图
        setInitialView() {
            // 设置初始位置(例如:北京天安门)
            const initialPosition = Cesium.Cartesian3.fromDegrees(116.3914, 39.9074, 1100)
            this.viewer.camera.setView({
                destination: initialPosition,
                orientation: {
                    heading: Cesium.Math.toRadians(0),
                    pitch: Cesium.Math.toRadians(-90),
                    roll: 0
                }
            })
        },

        /* ================= 添加示例实体 ================= */
        addDemoEntities() {
            const viewer = this.viewer

            // Billboard
            const billboard = this.viewer.entities.add({
                name: '图片',
                position: Cesium.Cartesian3.fromDegrees(116.3914, 39.9062),
                billboard: {
                    image: '/images/construction.png',
                    scale: 0.2,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.CENTER,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY // 强制始终可见
                }
            })
            this.sampleEntities.push(billboard)

            // Point
            const beijingPoint = this.viewer.entities.add({
                name: '北京天安门',
                position: Cesium.Cartesian3.fromDegrees(116.3914, 39.9070),
                point: {
                    pixelSize: 10,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2
                },
                label: {
                    text: '北京天安门',
                    font: '14pt sans-serif',
                    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                    outlineWidth: 2,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    pixelOffset: new Cesium.Cartesian2(0, -20),
                    disableDepthTestDistance: Number.POSITIVE_INFINITY // 关闭深度测试,防止被遮挡
                }
            })
            this.sampleEntities.push(beijingPoint)

            // Polygon
            const positions = [
                Cesium.Cartesian3.fromDegrees(116.3918, 39.9064),
                Cesium.Cartesian3.fromDegrees(116.3932, 39.9064),
                Cesium.Cartesian3.fromDegrees(116.3932, 39.9060),
                Cesium.Cartesian3.fromDegrees(116.3918, 39.9060)
            ]
            const polygon = this.viewer.entities.add({
                name: '多边形',
                polygon: {
                    hierarchy: new Cesium.PolygonHierarchy(positions),
                    material: Cesium.Color.GREEN.withAlpha(0.4),
                    outline: true,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 2,
                    height: 3 // 离地高度
                }
            })
            this.sampleEntities.push(polygon)

            // 添加GLB模型
            let modelEntity = this.viewer.entities.add({
                name: '模型',
                position: Cesium.Cartesian3.fromDegrees(116.3904, 39.9062, 0),
                model: {
                    uri: '/models/glb/car_type_0.glb',
                    minimumPixelSize: 64, // 在缩放时保持最小像素大小
                    scale: 1.0,
                    incrementallyLoadTextures: true, // 逐步加载贴图
                }
            })
            this.sampleEntities.push(modelEntity)
        },

        /* ================= 事件初始化 ================= */
        initPickEvents() {
            this.handler = new Cesium.ScreenSpaceEventHandler(
                this.viewer.scene.canvas
            )

            this.bindMouseMove()
            this.bindLeftClick()
        },

        /* ================= 鼠标悬停 ================= */
        bindMouseMove() {
            this.handler.setInputAction(movement => {
                const picked = this.viewer.scene.pick(movement.endPosition)

                // 没有拾取到实体
                if (!Cesium.defined(picked) || !picked.id) {
                    this.restoreHover(true)
                    return
                }

                const entity = picked.id

                // 同一个实体不重复处理
                if (this.hovered.entity === entity) return

                // 恢复上一次 hover(不影响选中)
                this.restoreHover(true)

                // 已选中的实体不参与 hover
                if (this.selected.entity === entity) return

                this.hovered.entity = entity
                this.highlight(entity, 'hover')
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        },

        /* ================= 鼠标点击 ================= */
        bindLeftClick() {
            this.handler.setInputAction(movement => {
                const picked = this.viewer.scene.pick(movement.position)

                // 恢复上一次选中
                this.restoreSelected()

                if (!Cesium.defined(picked) || !picked.id) return

                const entity = picked.id

                // 清除 hover
                this.restoreHover()

                this.selected.entity = entity
                this.highlight(entity, 'select')

                // 业务扩展点
                console.log('当前选中实体:', entity.id)
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
        },

        /* ================= 高亮处理 ================= */
        highlight(entity, type) {
            const color =
                type === 'hover'
                    ? Cesium.Color.YELLOW
                    : Cesium.Color.ORANGE

            const isSelect = type === 'select'

            /* ========== 1. GLB / Model 描边(最优方案) ========== */
            if (entity.model) {
                entity.model.silhouetteColor = color
                entity.model.silhouetteSize = isSelect ? 4.0 : 2.0
                return
            }

            /* ========== 2. Polygon 边框描边 ========== */
            if (entity.polygon) {
                const cache = isSelect ? this.selected : this.hovered
                cache.originalStyle = {
                    outline: entity.polygon.outline,
                    outlineColor: entity.polygon.outlineColor
                }

                entity.polygon.outline = true
                entity.polygon.outlineColor = color
                return
            }

            /* ========== 3. Point / Billboard 使用光圈 ========== */
            if (entity.point || entity.billboard) {
                const position = entity.position.getValue(
                    this.viewer.clock.currentTime
                )

                // 计算光圈大小(Billboard 使用固尺寸光圈,Point光圈更具原始点的大小动态设置)
                let radiusPx = 25
                if (entity.point) {
                    radiusPx = entity.point.pixelSize / 2 + 3
                }

                const ellipse = this.viewer.entities.add({
                    position,
                    ellipse: {
                        semiMajorAxis: radiusPx,
                        semiMinorAxis: radiusPx,
                        material: color.withAlpha(0.25),
                        outline: true,
                        outlineColor: color,
                        height: 0.1
                    }
                })

                if (isSelect) {
                    this.outlineAssist.selectEllipse = ellipse
                } else {
                    this.outlineAssist.hoverEllipse = ellipse
                }
            }
        },

        /* ================= 恢复 hover ================= */
        restoreHover(ignoreSelected = false) {
            const entity = this.hovered.entity
            if (!entity) return

            if (ignoreSelected && entity === this.selected.entity) return

            /* Model */
            if (entity.model) {
                entity.model.silhouetteSize = 0.0
            }

            /* Polygon */
            if (entity.polygon && this.hovered.originalStyle) {
                entity.polygon.outline = this.hovered.originalStyle.outline
                entity.polygon.outlineColor = this.hovered.originalStyle.outlineColor
            }

            /* 光圈 */
            if (this.outlineAssist.hoverEllipse) {
                this.viewer.entities.remove(this.outlineAssist.hoverEllipse)
                this.outlineAssist.hoverEllipse = null
            }

            this.hovered.entity = null
            this.hovered.originalStyle = null
        },

        /* ================= 恢复 selected ================= */
        restoreSelected() {
            const entity = this.selected.entity
            if (!entity) return

            /* Model */
            if (entity.model) {
                entity.model.silhouetteSize = 0.0
            }

            /* Polygon */
            if (entity.polygon && this.selected.originalStyle) {
                entity.polygon.outline = this.selected.originalStyle.outline
                entity.polygon.outlineColor = this.selected.originalStyle.outlineColor
            }

            /* 光圈 */
            if (this.outlineAssist.selectEllipse) {
                this.viewer.entities.remove(this.outlineAssist.selectEllipse)
                this.outlineAssist.selectEllipse = null
            }

            this.selected.entity = null
            this.selected.originalStyle = null
        },

        // 销毁 Cesium 资源
        destroyCesium() {
            if (this.handler) {
                this.handler.destroy()
                this.handler = null
            }
            if (this.viewer) {
                this.viewer.destroy()
                this.viewer = null
            }
        }
    }
}
</script>

<style scoped>
.layer-container {
    position: relative;
    width: 100%;
    height: 100%;
}


.cesium-container {
    width: 100%;
    height: 100%;
}

.loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    color: white;
}

.loading-spinner {
    border: 4px solid rgba(255, 255, 255, 0.3);
    border-radius: 50%;
    border-top: 4px solid #42b983;
    width: 50px;
    height: 50px;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>

2,运行效果

(1)页面打开时会自动加载展示图片标注(Billboard)、点位与文字标签、多边形区域以及一个 GLB 三维模型。

(2)用户移动鼠标时,指针下方的实体会产生悬停反馈:三维模型出现细描边高亮,多边形边框变为黄色,点位和图片标注周围生成一圈半透明的高亮光圈。当鼠标移出实体区域,高亮效果会立即恢复。




(3)点击任意实体后,该实体进入选中状态,高亮颜色变为橙色,同时自动清除之前的选中效果,并在控制台输出当前选中的实体信息。



评论

全部评论(0)

回到顶部