在智慧城市项目中,轨迹线一般用来表现城市道路的流动效果。和cesium动态线篇效果类似,只是这里是通过设置高亮占比,而不是通过传入一张图片。
1. 自定义TrialFlowMaterialProperty类
1.1. 自定义 TrialFlowMaterialProperty 类
/*
* @Description:
* @Author: maizi
* @Date: 2024-08-16 15:06:46
* @LastEditTime: 2024-08-26 17:47:26
* @LastEditors: maizi
*/
function TrialFlowMaterialProperty(options) {
options = Cesium.defaultValue(options, Cesium.defaultValue.EMPTY_OBJECT);
this._definitionChanged = new Cesium.Event();
this._color = undefined;
this._speed = undefined;
this._ratio = undefined;
this._tranparent = undefined;
this.color = options.color || Cesium.Color.fromBytes(0, 255, 255, 255);
this.speed = options.speed || 1;
this.ratio = options.ratio || 0.2;
this.tranparent = options.tranparent || 0.2;
}
Object.defineProperties(TrialFlowMaterialProperty.prototype, {
isConstant: {
get: function () {
return (
Cesium.Property.isConstant(this._color)
&& Cesium.Property.isConstant(this._speed)
&& Cesium.Property.isConstant(this._ratio)
&& Cesium.Property.isConstant(this._tranparent)
);
},
},
definitionChanged: {
get: function () {
return this._definitionChanged;
},
},
color: Cesium.createPropertyDescriptor("color"),
speed: Cesium.createPropertyDescriptor("speed"),
ratio: Cesium.createPropertyDescriptor("ratio"),
tranparent: Cesium.createPropertyDescriptor("tranparent"),
});
TrialFlowMaterialProperty.prototype.getType = function (time) {
return "TrialFlow";
};
TrialFlowMaterialProperty.prototype.getValue = function (time, result) {
if (!Cesium.defined(result)) {
result = {};
}
result.color = Cesium.Property.getValueOrClonedDefault(this._color, time);
result.speed = Cesium.Property.getValueOrClonedDefault(this._speed, time);
result.ratio = Cesium.Property.getValueOrUndefined(this._ratio, time);
result.tranparent = Cesium.Property.getValueOrUndefined(this._tranparent, time);
return result;
};
TrialFlowMaterialProperty.prototype.equals = function (other) {
const res = this === other || (other instanceof TrialFlowMaterialProperty &&
Cesium.Property.equals(this._color, other._color) &&
Cesium.Property.equals(this._speed, other._speed))&&
Cesium.Property.equals(this._ratio, other._ratio) &&
Cesium.Property.equals(this._tranparent, other._tranparent)
return res;
};
export default TrialFlowMaterialProperty;
1.2. 材质shader
uniform vec4 color;
uniform float speed;
uniform float ratio;
uniform float tranparent;
czm_material czm_getMaterial(czm_materialInput materialInput){
czm_material material = czm_getDefaultMaterial(materialInput);
vec2 st = materialInput.st;
float time = fract(czm_frameNumber * speed / 1000.0);
float alpha = smoothstep(time - ratio, time, st.s) * step(-time, -st.s);
alpha += tranparent;
material.diffuse= color.rgb;
material.alpha = alpha;
return material;
}
1.3. 添加到缓存
/*
* @Description:
* @Author: maizi
* @Date: 2024-08-16 16:21:55
* @LastEditTime: 2024-08-26 18:00:42
* @LastEditors: maizi
*/
import TrialFlowMaterial from '../shader/TrialFlowMaterial.glsl'
Cesium.Material.TrialFlow = 'TrialFlow'
Cesium.Material._materialCache.addMaterial(
Cesium.Material.TrialFlow,
{
fabric: {
type: Cesium.Material.TrialFlow,
uniforms: {
color: new Cesium.Color(1.0, 0.0, 0.0, 0.7),
speed: 1,
ratio: 0.2,
tranparent: 0.2
},
source: TrialFlowMaterial,
},
translucent: function (material) {
return true
},
}
)
2. 完整示例代码
TrialFlowLine.js
/*
* @Description:
* @Author: maizi
* @Date: 2022-05-27 11:36:22
* @LastEditTime: 2023-04-26 17:38:41
* @LastEditors: maizi
*/
const merge = require('deepmerge')
import { TrialFlowMaterialProperty } from '../../materialProperty/index.js'
const defaultStyle = {
speed: 10,
ratio: 0.2,
tranparent: 0.2,
color: "#ffff00",
lineWidth: 8
}
class TrialFlowLine {
constructor(viewer, coords, options = {}) {
this.viewer = viewer
this.coords = coords;
this.options = options;
this.props = this.options.props;
this.style = merge(defaultStyle, this.options.style || {});
this.entity = null;
this.material = null
this.points = []
this.init();
}
init() {
this.createMaterial();
this.entity = new Cesium.Entity({
id: Math.random().toString(36).substring(2),
type: "trial_flow_line",
polyline: {
positions: this.getPositons(),
width: this.style.lineWidth,
material: this.material,
//clampToGround: true
}
});
}
addPoints() {
this.coords.forEach((coord) => {
const point = new Cesium.Entity({
position: Cesium.Cartesian3.fromDegrees(coord[0],coord[1],coord[2]),
point: {
color: Cesium.Color.DARKBLUE.withAlpha(.4),
pixelSize: 6,
outlineColor: Cesium.Color.YELLOW.withAlpha(.8),
outlineWidth: 4
}
});
this.viewer.entities.add(point)
this.points.push(point)
})
}
removePoints() {
this.points.forEach((point) => {
this.viewer.entities.remove(point)
})
this.points = []
}
getPositons() {
const positions = []
this.coords.forEach((coord) => {
positions.push(Cesium.Cartesian3.fromDegrees(coord[0], coord[1], coord[2]));
})
return positions
}
createMaterial() {
this.material = new TrialFlowMaterialProperty({
color: new Cesium.Color.fromCssColorString(this.style.color),
speed:this.style.speed,
ratio: this.style.ratio,
tranparent: this.style.tranparent
});
}
updateStyle(style) {
this.style = merge(defaultStyle, style);
this.entity.polyline.width = this.style.lineWidth
this.material.color = new Cesium.Color.fromCssColorString(this.style.color)
this.material.speed = this.style.speed
this.material.ratio = this.style.ratio
this.material.tranparent = this.style.tranparent
}
setSelect(enabled) {
if (enabled) {
this.addPoints()
} else {
this.removePoints()
}
}
}
export {
TrialFlowLine
}
MapWorks.js
import GUI from 'lil-gui';
// 初始视图定位在中国
import { TrialFlowLine } from './TrialFlowLine'
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);
let viewer = null;
let graphicLayer = null
let graphicList = []
let selectGraphic = null
let eventHandler = null
let gui = null
function initMap(container) {
viewer = new Cesium.Viewer(container, {
animation: false,
baseLayerPicker: false,
fullscreenButton: false,
geocoder: false,
homeButton: false,
infoBox: false,
sceneModePicker: false,
selectionIndicator: false,
timeline: false,
navigationHelpButton: false,
scene3DOnly: true,
orderIndependentTranslucency: false,
contextOptions: {
webgl: {
alpha: true
}
}
})
viewer._cesiumWidget._creditContainer.style.display = 'none'
viewer.scene.fxaa = true
viewer.scene.postProcessStages.fxaa.enabled = true
if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
// 判断是否支持图像渲染像素化处理
viewer.resolutionScale = window.devicePixelRatio
}
// 移除默认影像
removeAll()
// 地形深度测试
viewer.scene.globe.depthTestAgainstTerrain = true
// 背景色
viewer.scene.globe.baseColor = new Cesium.Color(0.0, 0.0, 0.0, 0)
// 太阳光照
viewer.scene.globe.enableLighting = true;
// 初始化图层
initLayer()
// 初始化鼠标事件
initClickEvent()
//调试
window.viewer = viewer
}
function initGui() {
let params = {
...selectGraphic.style
}
gui = new GUI()
let layerFolder = gui.title('样式设置')
layerFolder.add(params, 'speed', 0, 100).step(1.0).onChange(function (value) {
selectGraphic.updateStyle(params)
})
layerFolder.add(params, 'ratio', 0, 1.0).step(0.01).onChange(function (value) {
selectGraphic.updateStyle(params)
})
layerFolder.add(params, 'tranparent', 0, 1.0).step(0.01).onChange(function (value) {
selectGraphic.updateStyle(params)
})
layerFolder.add(params, 'lineWidth', 1, 30).step(1).onChange(function (value) {
selectGraphic.updateStyle(params)
})
layerFolder.addColor(params, 'color').onChange(function (value) {
selectGraphic.updateStyle(params)
})
}
function initLayer() {
const layerProvider = new Cesium.ArcGisMapServerImageryProvider({
url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
});
viewer.imageryLayers.addImageryProvider(layerProvider);
graphicLayer = new Cesium.CustomDataSource('graphicLayer')
viewer.dataSources.add(graphicLayer)
}
function loadTrialFlowLine(lines) {
lines.forEach(line => {
const trialFlowLine = new TrialFlowLine(viewer, line.points)
graphicList.push(trialFlowLine)
graphicLayer.entities.add(trialFlowLine.entity)
});
viewer.flyTo(graphicLayer)
}
function initClickEvent() {
eventHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
initLeftClickEvent()
initMouseMoveEvent()
}
function initLeftClickEvent() {
eventHandler.setInputAction((e) => {
if (selectGraphic) {
selectGraphic.setSelect(false)
selectGraphic = null
}
if (gui) {
gui.destroy()
}
let pickedObj = viewer.scene.pick(e.position);
if (pickedObj && pickedObj.id) {
if (pickedObj.id.type === 'trial_flow_line') {
selectGraphic = getGraphicById(pickedObj.id.id)
if (selectGraphic) {
selectGraphic.setSelect(true)
initGui()
}
}
}
},Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
function initMouseMoveEvent() {
eventHandler.setInputAction((e) => {
const pickedObj = viewer.scene.pick(e.endPosition);
if (pickedObj && pickedObj.id) {
if (pickedObj.id.type === 'trial_flow_line') {
// 改变鼠标状态
viewer._element.style.cursor = "";
document.body.style.cursor = "pointer";
} else {
viewer._element.style.cursor = "";
document.body.style.cursor = "default";
}
} else {
viewer._element.style.cursor = "";
document.body.style.cursor = "default";
}
},Cesium.ScreenSpaceEventType.MOUSE_MOVE)
}
function getGraphicById(id) {
let line = null
for (let i = 0; i < graphicList.length; i++) {
if (graphicList[i].entity.id === id) {
line = graphicList[i]
break
}
}
return line
}
function removeAll() {
viewer.imageryLayers.removeAll();
}
function destroy() {
viewer.entities.removeAll();
viewer.imageryLayers.removeAll();
viewer.destroy();
}
export {
initMap,
loadTrialFlowLine,
destroy
}
TrialFlowLine.vue
<!--
* @Description:
* @Author: maizi
* @Date: 2023-04-07 17:03:50
* @LastEditTime: 2024-08-26 18:00:57
* @LastEditors: maizi
-->
<template>
<div id="container">
</div>
</template>
<script>
import * as MapWorks from './js/MapWorks'
export default {
name: 'TrialFlowLine',
mounted() {
this.init();
},
methods:{
init(){
let container = document.getElementById("container");
MapWorks.initMap(container)
//创建
let lines = [
{
points: [
[104.068822,30.654807,10],
[104.088822,30.654807,10],
]
},
{
points: [
[104.068822,30.655807,10],
[104.088822,30.655807,10],
]
},
];
MapWorks.loadTrialFlowLine(lines)
}
},
beforeDestroy(){
//实例被销毁前调用,页面关闭、路由跳转、v-if和改变key值
MapWorks.destroy();
}
}
</script>
<style lang="scss" scoped>
#container{
width: 100%;
height: 100%;
background: rgba(7, 12, 19, 1);
overflow: hidden;
background-size: 40px 40px, 40px 40px;
background-image: linear-gradient(hsla(0, 0%, 100%, 0.05) 1px, transparent 0), linear-gradient(90deg, hsla(0, 0%, 100%, 0.05) 1px, transparent 0);
}
</style>