Cesium有很多很强大的功能,可以在地球上实现很多炫酷的3D效果。今天给大家分享一个视频融合功能。

1.话不多说,先展示

【Cesium开发实战】视频融合功能的实现,可自定义位置和视频路径_视频融合

视频:Cesium视频融合

2.设计思路

点击绘制开始在地图上绘制视频融合的点位,形成视频播放的区域,双击弹框输入名称和要播放视频的路径,即可对应区域播放对应视频,点击删除可删除内容

3.具体代码

<template>

  <div class="page">
    <el-button @click="drawExtent">绘制</el-button>
    <el-table :data="dataList" v-loading="loading" border @row-click="rowClick">
      <el-table-column prop="name" label="名称" align="center" />
      <el-table-column prop="action" label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="delEntity(scope.row, scope.$index)"><el-icon
              :size="16"><ele-Delete /> </el-icon></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <el-dialog v-model="dialogFormVisible" title="配置" width="500" :close-on-press-escape="false"
    :close-on-click-modal="false" :show-close="false">
    <el-form ref="formRef" :model="form" label-width="auto" :rules="rules">
      <el-form-item label="融合名称:" prop="title">
        <el-input v-model="form.title" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="视频地址:" prop="address">
        <el-input v-model="form.address" placeholder="请输入" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(formRef)"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import * as Cesium from 'cesium';
import Hls from 'hls.js';
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import * as api from "/@/api/main/shiPRH";

const loading = ref(false);
const props = defineProps(['viewer']);
const dataList: any = reactive([]);

const formRef = ref();
const rules = {
  title: { required: true, message: '请输入融合名称', trigger: 'blur' },
  address: { required: true, message: '请输入视频地址', trigger: 'blur' },
};

// 弹框内容
const form = reactive({
  title: '',
  address: '',
});

const dialogFormVisible = ref(false);

//临时点位
let points: any = [];
//临时实体(画的点位)
let tempEntities: any = [];

var listEntities: any = [];
//数据源
let data: any = [];
let handler: any = null;
//是否开始绘制
const drawing = ref(false);

//绘制点位
const drawExtent = () => {

  drawing.value = true;

  handler = new Cesium.ScreenSpaceEventHandler(props.viewer.canvas);

  //左键开始绘制

  handler.setInputAction((event:any) => {
    if (drawing.value) {
      const cartesian = props.viewer.scene.pickPosition(event.position);
      if (Cesium.defined(cartesian)) {
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        let pickedPosition = {
          longitude: Cesium.Math.toDegrees(cartographic.longitude),
          latitude: Cesium.Math.toDegrees(cartographic.latitude),
          height: cartographic.height, // 如果需要高度信息也可以获取  
        };
        tempEntities.push(createPoint(cartesian));
        points.push(pickedPosition);
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  //双击结束绘制
  handler.setInputAction(() => {
    if (drawing.value) {
      drawing.value = false;
      dialogFormVisible.value = true;
    }
    if (handler != null) {
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
      handler.destroy();// 关闭事件句柄
      handler = null;
    }
    props.viewer.trackedEntity = null;//为了去除双击后锁定无法移动视角
  }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
}

var flyOption = {
	offset: {
		heading: Cesium.Math.toRadians(1.0114629015290062),
		pitch: Cesium.Math.toRadians(-23.53661660731824),
		roll: Cesium.Math.toRadians(0.00324596311071617),
	},
};

/**
 * 点击表格一行
 */
 const rowClick = (row: any, column: any, event: Event) => {
	if (column && column.property) {
		let index = dataList.findIndex((v: any) => v.id === row.id);
		if (index !== -1) {
			props.viewer.flyTo(listEntities[index]);
		}
	}
};

/**
 * 删除已绘制的图形
 */
const delEntity = async (item: any, index: number) => {

	await Delete(item, index);
};

/**
 * 点击确定绘制
 */
const submitForm = async (formEl: any) => {
  const valid = await formEl.validate();
  if (valid) {
    Save(form.title, form.address);
    dialogFormVisible.value = false;
    formEl.resetFields();
  }
};

//创建点位
const createPoint = (worldPosition: any) => {
  const point = props.viewer.entities.add({
    position: worldPosition,
    point: {
      color: Cesium.Color.RED,
      pixelSize: 10,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
    },
  });
  return point;
};

/**
 * 清除
 */
const clearAllEntities = () => {


  points = [];
  tempEntities = [];
  data = [];

  //移除所有对象
  props.viewer.entities.removeAll();
  if (handler) {
    handler.destroy();
    handler = undefined;
  }
};

onMounted(async () => {
  await handleQuery();
});

onUnmounted(() => {
  clearAllEntities()
});


/**
 * 删除信息
 */
const Delete = async (item: any, index: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    var res = await api.deleteShiPRH({ id: item.id });
    console.log(res);
    if (res.data.type == "success") {
      //清除地图上的实体
      props.viewer.entities.remove(listEntities[index]);
      listEntities.splice(index, 1);
      dataList.splice(index, 1);
      ElMessage.success("删除成功");
    }
    loading.value = false;
  }).catch(() => { });
}

/**
 * 查询
 */
const handleQuery = async () => {
  loading.value = true;
  var res = await api.listShiPRH();
  console.log(res);
  if (res.data.code == 200 && res.data.result) {
    for (const item of res.data.result) {
      showResult(item);
    }
  }
  loading.value = false;
}

/**
 * 保存电子围栏信息
 */
const Save = async (name: string, address: any,) => {

  for (let item of points) {
    data.push(item.longitude);
    data.push(item.latitude);
    data.push(item.height);
  }

  var param = {
    'mingCh': name,
    'shiPDZh': address,
    '_CoordinateInfoList': Cesium.Cartesian3.fromDegreesArrayHeights(data)
  };

  var res = await api.addShiPRH(param);
  console.log(res);
  if (res.data.code == 200 && res.data.result) {
    ElMessage.success("视频融合添加成功");
    initVideo(res.data.result);
  }
}

const initVideo = (item: any) => {


  var video = document.createElement('video');

  // 设置video的属性  
  video.src = item.shiPDZh; // 设置视频源  
  video.controls = true; // 显示控件,如播放/暂停按钮  
  video.autoplay = true; // 是否自动播放(根据需要设置)  
  video.muted = true; // 是否静音(根据需要设置)  
  video.loop = true; // 是否循环播放(根据需要设置) 
  video.playsInline = true;

  if (video) {
    var hls = new Hls();
    hls.loadSource(item.shiPDZh);
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
      video.play();
    });
  }

  props.viewer.showRenderLoopErrors = false;
  props.viewer.shouldAnimate = true;

  var entitity = props.viewer.entities.add({
    polygon: {
      hierarchy: item._CoordinateInfoList,
      material: video, // 将材质设置为video元素
      clampToGround: true,
    },
  });

  for (const item of tempEntities) {
    props.viewer.entities.remove(item);
  }

  listEntities.push(entitity);

  dataList.push({
    id: item.id,
    name: item.mingCh,
  });


  //双击清空数据
  points = [];
  tempEntities = [];
  data = [];
}

/**
 * 添加视频融合
 */
var showResult = (item: any) => {

  var video = document.createElement('video');

// 设置video的属性  
video.src = item.shiPDZh; // 设置视频源  
video.controls = true; // 显示控件,如播放/暂停按钮  
video.autoplay = true; // 是否自动播放(根据需要设置)  
video.muted = true; // 是否静音(根据需要设置)  
video.loop = true; // 是否循环播放(根据需要设置) 
video.playsInline = true;

if (video) {
  var hls = new Hls();
  hls.loadSource(item.shiPDZh);
  hls.attachMedia(video);
  hls.on(Hls.Events.MANIFEST_PARSED, function () {
    video.play();
  });
}

props.viewer.showRenderLoopErrors = false;
props.viewer.shouldAnimate = true;

var entitity = props.viewer.entities.add({
  polygon: {
    hierarchy: item._CoordinateInfoList,
    material: video, // 将材质设置为video元素
    clampToGround: true,
  },
});

listEntities.push(entitity);

  dataList.push({
    id: item.id,
    name: item.mingCh,
  });

};

</script>
<style scoped>
.page {
  position: absolute;
  right: 10px;
  top: 10px;
  color: #fff;
  background: #fff;
  padding: 10px;
  border-radius: 5px;
  width: 300px;
}
</style>

4.注意事项

本文章使用的视频地址是:https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8,后缀为m3u8的格式。需要引入hls.js的内容。