DrawMap.js
/*
绘制矩形范围,截图保存到本地
*/
import VectorSource from 'ol/source/Vector';
import Draw, {
createBox
} from 'ol/interaction/Draw'
import {
Fill,
Stroke,
Style
} from 'ol/style';
// 绘制矩形后,截图保存到本地
export function drawMap(map, imgName) {
const source = new VectorSource({
wrapX: false
});
let draw = new Draw({
source: source,
type: 'Circle',
style: new Style({
stroke: new Stroke({
color: 'blue',
width: 2,
}),
fill: new Fill({
color: 'rgba(0, 0, 0, 0)',
}),
}),
geometryFunction: createBox()
})
map.addInteraction(draw);
draw.on('drawend', (evt) => {
// source.clear();
map.removeInteraction(draw);
console.log(evt);
map.renderSync();
let extent = evt.feature.getGeometry().getExtent();
//地理坐标转换屏幕坐标
let coord = [extent[0], extent[3]];
let leftTopPosition = map.getPixelFromCoordinate(coord);
let coord1 = [extent[2], extent[1]];
let bottomRightPosition = map.getPixelFromCoordinate(coord1);
//计算框选矩形的宽度以及高度像素
let width = Math.abs(bottomRightPosition[0] - leftTopPosition[0]);
let height = Math.abs(bottomRightPosition[1] - leftTopPosition[1]);
//计算框选矩形的左上角屏幕坐标
let minx = leftTopPosition[0];
let miny = leftTopPosition[1];
//创建canvas元素
let mapCanvas = document.getElementsByClassName("ol-layer")[0].children[0];
let imageData = mapCanvas.getContext("2d").getImageData(minx, miny, width, height);
let canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").putImageData(imageData, 0, 0);
let dataUrl = canvas.toDataURL(); //转换图片为dataURL
let link = document.createElement('a');
link.download = imgName;
link.href = dataUrl;
link.click();
console.log("截图成功");
})
}