自定義飛線材質 FlyLineMaterial.ts
import * as Cesium from "cesium" ; // 修改:新增流動區域顏色和速率參數
const FlyLineShaderSource = `
uniform vec4 color;
uniform vec4 flowColor;
uniform float percent;
uniform float speed; czm_material czm_getMaterial( czm_materialInput materialInput) { vec4 outColor = color; czm_material material = czm_getDefaultMaterial( materialInput) ; vec2 st = materialInput.st; float time = fract( czm_frameNumber * speed / 144.0 ) ; float startPosition = time ; if( st.s > startPosition - percent && st.s < startPosition) { float value = ( st.s - ( startPosition - percent)) / percent; outColor.rgb = mix( color.rgb, flowColor.rgb, value) ; } material.diffuse = czm_gammaCorrect( outColor.rgb) ; material.alpha = outColor.a; return material;
} ` ; type FlyLineOptions = { color: Cesium.Color; // 線主體顏色flowColor: Cesium.Color; // 流動線顏色percent: number; //流動區域占整個線段的比例(0~1)speed: number; //流動速度
} ; export class FlyLineMaterial extends Cesium.Material { constructor( options: FlyLineOptions) { const { color, flowColor, percent, speed } = options; // 解構參數super( { translucent: false,fabric: { type: "FlyLine" ,uniforms: { color,flowColor, // 新增:流動區域顏色percent,speed, // 新增:流動速度} ,source: FlyLineShaderSource, // 使用抽離的著色器代碼} ,} ) ; }
}
使用飛線材質
const positions = Cesium.Cartesian3.fromDegreesArray( [ 125.321753 , 43.810582 , 126.554969 , 43.834361 ,] ) ; // 創建幾何const geometry = new Cesium.PolylineGeometry( { positions: positions,width: 1 ,} ) ; const instance = new Cesium.GeometryInstance( { geometry: geometry,} ) ; const appearance = new Cesium.PolylineMaterialAppearance( { material: new FlyLineMaterial( { color: Cesium.Color.fromCssColorString( "#2d7367" ) ,flowColor: Cesium.Color.fromCssColorString( "#2ddcab" ) ,percent: 0.1 ,speed: 0.5 ,} ) ,} ) ; const primitive = new Cesium.Primitive( { geometryInstances: instance,appearance: appearance,} ) ; viewer.scene.primitives.add( primitive) ;