Skip to content

地图导出

导出图片

vue
<template>
  <div id="cesiumContainer"></div>
  <button @click="saveToImage">导出图片</button>
</template>

<script setup lang="ts">
  import { onMounted } from "vue";
  import * as Cesium from "cesium";

  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMGM1ODNmMi01NjgxLTRiNjYtYjEzYS0xMWZhODZlNDIyOWIiLCJpZCI6MTE2MzEzLCJpYXQiOjE3MzY2NjMwNjN9.tTeB32oDNJyNSn7iecCvMb2O5ETRw56CmX_OCSsMu34";

  let viewer: Cesium.Viewer;

  onMounted(() => {
    viewer = new Cesium.Viewer("cesiumContainer", {
      infoBox: false
    });
  });

  /** 利用 base64 导出为 png 图片 */
  function saveToImage() {
    // 不写会导出为黑图
    viewer.render();

    const canvas = viewer.scene.canvas;
    const imageUrl = canvas.toDataURL("image/png");
    // 创建<a />标签,模拟点击下载图片的操作
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = imageUrl;
    tempLink.download = "图片.png";
    tempLink.click();
  }
</script>

<style scoped>
  button {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 100px;
    height: 40px;
    border-radius: 5px;
  }
</style>
vue
<template>
  <div id="cesiumContainer"></div>
  <button @click="saveToImage">导出图片</button>
</template>

<script setup lang="ts">
  import { onMounted } from "vue";
  import * as Cesium from "cesium";

  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMGM1ODNmMi01NjgxLTRiNjYtYjEzYS0xMWZhODZlNDIyOWIiLCJpZCI6MTE2MzEzLCJpYXQiOjE3MzY2NjMwNjN9.tTeB32oDNJyNSn7iecCvMb2O5ETRw56CmX_OCSsMu34";

  let viewer: Cesium.Viewer;

  onMounted(() => {
    viewer = new Cesium.Viewer("cesiumContainer", {
      infoBox: false
    });
  });

  /** 利用 blob 导出为 png 图片 */
  function saveToImage() {
    // 不写会导出为黑图
    viewer.render();

    const canvas = viewer.scene.canvas;
    const imageUrl = canvas
      .toDataURL("image/png")
      .replace("image/png", "image/octet-stream");
    const objUrl = URL.createObjectURL(dataURLtoBlob(imageUrl));
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = objUrl;
    tempLink.download = "图片.png";
    tempLink.click();
  }

  /**
 * 将base64格式的url转换为blob对象
 * @param dataUrl
 */
  function dataURLtoBlob(dataUrl: string) {
    const arr = dataUrl.split(",");
    // 提取mime类型,例如image/png
    const mime = arr[0].match(/:(.*?);/)![1];
    // 解码 base64 数据
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }
</script>

<style scoped>
  button {
    position: absolute;
    top: 20px;
    left: 20px;
    width: 100px;
    height: 40px;
    border-radius: 5px;
  }
</style>

Released under the MIT License.