Skip to content

Print

Output the map as an image, only the visible map area and all layers will be output.

  • You need to set preserveDrawingBuffer to true.
  • You can print high-definition images by globally setting the devicePixelRatio value.
ts
const dpi = 300
Object.defineProperty(window, 'devicePixelRatio', {
  get() { return dpi / 96 },
})

Example



Example Source Code
vue
<template>
  <div style="height: 400px" class="vw-full vh-full">
    <button class="primary" @click="print">打印(Print)</button>
    <mb-map
      :zoom="mapZoom"
      :center="mapCenter"
      :extend-props="{ preserveDrawingBuffer: true }"
      @created="mapCreatedHandler"
    >
      <mb-tianditu-layer />
      <mb-polygon-layer
        v-if="showLayer"
        source-id="sourceExample"
        :opacity="0.1"
        color="blue"
      />
      <mb-polyline-layer
        v-if="showLayer"
        source-id="sourceExample"
        color="blue"
      />
      <mb-source
        id="sourceExample"
        :geo-json-source="geoJsonSource"
        @source-added="showLayer = true"
      />
    </mb-map>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import type { Map } from 'mapbox-gl'

let $map: Map | null = null

const mapCenter = [120.30782359643746, 31.49292271319491]
const mapZoom = 11
const showLayer = ref(false)
const geoJsonSource = {
  type: 'geojson',
  data: `${__RESOURCE_URL__}json/source-example.geojson`,
}

const mapCreatedHandler = (map: Map) => {
  $map = map
}
const print = () => {
  const img = $map?.getCanvas().toDataURL('image/png')
  const link = document.createElement('a')
  link.setAttribute('href', img)
  link.setAttribute('download', 'test.png')
  document.body.appendChild(link)
  link.click()
}
</script>