下载地图官方示例:
我这儿使用到了 file-saver (下载图片、附件)
npm install file-saver --save
import { saveAs } from 'file-saver';
- // 执行下载
- download() {
- this.chartMap.once("rendercomplete", () => {
- const mapCanvas = document.createElement("canvas");
- const size = this.chartMap.getSize();
- console.log(size);
- mapCanvas.width = size[0];
- mapCanvas.height = size[1];
- const mapContext = mapCanvas.getContext("2d");
- Array.prototype.forEach.call(
- this.chartMap
- .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) {
- 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 = "#192A3D";
- 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);
- let href = mapCanvas.toDataURL();
- saveAs(href, "万家寨水轮机.png");
- });
- this.chartMap.renderSync();
- },