OpenLayers地图打印输出
最近遇到了在Openlayers上开发地图打印的功能,官网给了两个全图打印的demo。其核心思想是将canvas里的像素提取出来。
- 全图输出,保存为本地图片
map.once("postcompose", function(event) {
var canvas = event.context.canvas;
if (navigator.msSaveBlob) {
navigator.msSaveBlob(canvas.msToBlob(), "map.png");
} else {
canvas.toBlob(function(blob) {
FileSaverJS.saveAs(blob, "map.png");
});
}
});
map.renderSync();
利用上面代码,可以直接将canvas里图像输出,保存为本地图片;
- 截取范围,进行打印输出
原理是在
1屏幕上画矩形,然后获取矩形经纬度坐标;
2将矩形经纬度坐标转为canvas坐标
this._map.once("postrender", function (e) {
var extent = [];
extent[0] = e.target.getPixelFromCoordinate(that.bounds[0]);
extent[1] = e.target.getPixelFromCoordinate(that.bounds[1]);
extent[2] = e.target.getPixelFromCoordinate(that.bounds[2]);
extent[3] = e.target.getPixelFromCoordinate(that.bounds[3]);
});
3从canvas中提取相应的像素信息
//向内修改范围
getXDis(e, number) {
var min = undefined;
var max = undefined;
e.forEach(element => {
if (min == undefined || element[number] < min) {
min = element[number];
}
if (max == undefined || element[number] > max) {
max = element[number];
}
});
return [min+2, max - min-4];
}
var x_dx = that.getXDis(extent, 0);
var y_dy = that.getXDis(extent, 1);
console.log(x_dx);
console.log(y_dy);
let map = that.$store.state.map2d;
map.once("postcompose", function(event) {
var canvas = event.context.canvas;
var ctx = canvas.getContext("2d");
var image = ctx.getImageData(x_dx[0], y_dy[0], x_dx[1], y_dy[1]);
that.imageData = image;
});
map.renderSync();
最后将提取出来的像素信息,付给其他的canvas,结果如下图所示:
手机拍的不清楚,这是选取范围
下面是提取出来的结果
如果你觉得可以的话,可以打赏一下
转载自:https://blog.csdn.net/GISuuser/article/details/80353022