1、 导入FileSaver.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
2、设置数据源跨域
crossOrigin: “Anonymous”
const key = '8a5c2b00e94b49659861e064c37f778d'
/* 天地图矢量图层 */
const TianDiMap_vec = new ol.layer.Tile({
title: "天地图矢量图层",
source: new ol.source.XYZ({
url: 'http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=' +
key,
wrapX: false,
crossOrigin: "Anonymous"
})
})
/* 天地图注记图层 */
const TianDiMap_cva = new ol.layer.Tile({
title: "天地图矢量注记图层",
source: new ol.source.XYZ({
url: 'http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=' +
key,
wrapX: false,
crossOrigin: "Anonymous"
})
})
3、下载
<body>
<button onclick="exportImg()">导出图片</button>
<div id="map_container">
</div>
<script>
var map = new ol.Map({
target: "map_container",
layers: [TianDiMap_vec, TianDiMap_cva],
view: new ol.View({
center: [114, 30],
projection: 'EPSG:4326',
zoom: 4
})
})
function exportImg() {
map.once('postcompose', function (event) {
const canvas = event.context.canvas
console.log(canvas)
canvas.toBlob(function (blob) {
console.log(blob)
saveAs(blob, 'map.png')
})
})
map.renderSync()
}
</script>
</body>
4、如果是图层中有地图文档,也需设置跨域
var docLayer = new Zondy.Map.Doc("",docName , {
ip: "localhost",
port: 6163,
crossOrigin: "Anonymous"
});