openlayers 实现 地图导出功能
首先创建一个容器
<div class="exportMapImgCard">
<el-button type="primary" id="export-png" @click="exportMapImg"
>导出图片</el-button
>
<a id="image-download" download="map.png"></a>
</div>
data(){
Loading: false,
}
在mothods里
exportMapImg(){
let _that = this;
this.Loading = this.$loading({
lock: true,
text: "下载中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.3)",
});
const map = window.map //地图赋值
map.once('postcompose', function () {
const mapCanvas = document.createElement('canvas');
console.log(mapCanvas,"mapCanvas");
const size = map.getSize();
mapCanvas.width = size[0];
mapCanvas.height = size[1];
const mapContext = mapCanvas.getContext('2d');
Array.prototype.forEach.call(
map.getViewport().querySelectorAll('.ol-layer canvas, canvas.ol-layer'),
function (canvas) {
if (canvas.width > 0) {
const opacity =
canvas.parentNode.style.opacity || canvas.style.opacity;
mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
let matrix;
const transform = canvas.style.transform;
if (transform) {
// Get the transform parameters from the style's transform matrix
matrix = transform
.match(/^matrix\(([^\(]*)\)$/)[1]
.split(',')
.map(Number);
} else {
matrix = [
parseFloat(canvas.style.width) / canvas.width,
0,
0,
parseFloat(canvas.style.height) / canvas.height,
0,
0,
];
}
CanvasRenderingContext2D.prototype.setTransform.apply(
mapContext,
matrix
);
const backgroundColor = canvas.parentNode.style.backgroundColor;
if (backgroundColor) {
mapContext.fillStyle = backgroundColor;
mapContext.fillRect(0, 0, canvas.width, canvas.height);
}
mapContext.drawImage(canvas, 0, 0);
}
}
);
mapContext.globalAlpha = 1;
mapContext.setTransform(1, 0, 0, 1, 0, 0);
_that.Loading.close();
const link = document.getElementById('image-download');
link.href = mapCanvas.toDataURL();
link.click();
})
map.renderSync();
},
如果控制台报错 就是跨域了 解决方法在地图上配置跨域的方法 crossOrigin: ‘anonymous’
var world_adm0 = new Tile({
source: new TileWMS({
url: mapUrl,
crossOrigin: 'anonymous', //这个方法
params: {
LAYERS: "xxx",
TILED: true, //是否要将数据制作成切片,省略后返回的是一张完整图。
},
serverType: "geoserver",
projection: "EPSG:4326",
}),
name: "world_adm0",
});