地图打印(Print)
输出地图为图片格式,只能输出可视区域地图以及所有的图层。
- 需要设置preserveDrawingBuffer为true
- 可以通过全局设置devicePixelRatio值打印高清图片
ts
const dpi = 300
Object.defineProperty(window, 'devicePixelRatio', {
get: function() { return dpi / 96 },
})
示例
示例源码
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>