You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CesiumJS中如何使PolylineDash材质的GroundPolylinePrimitive保持静态

解决Cesium中GroundPolylinePrimitive虚线随相机移动偏移的问题

问题场景

使用GroundPolylinePrimitive搭配PolylineDash材质绘制地面折线时,移动相机后发现虚线图案会随视角偏移,无法固定在地面上保持静态。

核心原因

Cesium默认的PolylineDash材质是基于相机空间计算虚线的偏移量,而非世界空间,相机移动时,虚线的动画基准随之改变,导致视觉上折线“跟着移动”。


方法一:修改材质参考系属性

PolylineDash材质内置了referenceFrame参数,将其设置为ReferenceFrame.FIXED(世界空间)即可让虚线图案绑定到地面坐标,不再随相机移动:

let countyBorderPrimitive = new Cesium.GroundPolylinePrimitive({
    geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.GroundPolylineGeometry({
            positions: Cesium.Cartesian3.fromDegreesArray(newBorPos),
            width: 3,
        })
    }),
    show: stores.groundStore.visibleStatus,
    appearance: new Cesium.PolylineMaterialAppearance({
        material: Cesium.Material.fromType('PolylineDash', {
            color: Cesium.Color.RED,
            dashLength: 50,
            dashPattern: 255,
            // 设置参考系为世界空间,固定虚线位置
            referenceFrame: Cesium.ReferenceFrame.FIXED
        })
    })
});
cesium.scene.groundPrimitives.add(countyBorderPrimitive);

方法二:自定义着色器实现静态虚线

如果默认材质的参数无法满足需求,可自定义基于世界空间计算的着色器材质,完全控制虚线的生成逻辑:

// 自定义静态虚线材质
let staticDashMaterial = new Cesium.Material({
    fabric: {
        uniforms: {
            color: Cesium.Color.RED,
            dashLength: 50.0,
            dashRatio: 0.5 // 虚线占比,0.5表示虚实各半
        },
        source: `
            czm_material czm_getMaterial(czm_materialInput materialInput)
            {
                czm_material material = czm_getDefaultMaterial(materialInput);
                
                // 基于世界空间坐标计算虚线纹理坐标,确保固定
                float linePos = materialInput.worldPosition.x + materialInput.worldPosition.y + materialInput.worldPosition.z;
                float dashPos = mod(linePos, dashLength);
                
                // 生成虚线透明度
                material.alpha = step(dashPos, dashLength * dashRatio) * color.a;
                material.diffuse = color.rgb;
                
                return material;
            }
        `
    }
});

// 创建地面折线
let countyBorderPrimitive = new Cesium.GroundPolylinePrimitive({
    geometryInstances: new Cesium.GeometryInstance({
        geometry: new Cesium.GroundPolylineGeometry({
            positions: Cesium.Cartesian3.fromDegreesArray(newBorPos),
            width: 3,
        })
    }),
    show: stores.groundStore.visibleStatus,
    appearance: new Cesium.PolylineMaterialAppearance({
        material: staticDashMaterial
    })
});
cesium.scene.groundPrimitives.add(countyBorderPrimitive);

内容的提问来源于stack exchange,提问作者TixeT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:22:38