其他分享
首页 > 其他分享> > 【随手记录】关于openlayer打印输出地图

【随手记录】关于openlayer打印输出地图

作者:互联网

最近用openlayer做打印时候遇到打印空白、报错等问题,网上现有的说法大都是粘贴复制的,比如:
map.once("postrender", function(event) {
    // 以下方法在 ol 6.4.3版本无效, event.context为undefined
    var canvas = event.context.canvas;
    debugger;
    console.log(canvas.toDataURL("image/jpeg"));
})
换了种方式: 1、重新定义一个canvas
var r = $("#map").find("canvas");
if (r) {
    var newCanvas = document.createElement("canvas");
    newCanvas.width = r[0].width;
    newCanvas.height = r[0].height;
    for (let i = 0; i < r.length; i++) {
        if (r[i].width && r[i].height) {
            newCanvas.getContext("2d").drawImage(r[i],0,0)
        }
    }
    // data URI scheme
    var url = newCanvas.toDataURL("image/jpeg");
    console.log(url);
    var a = document.createElement('a');
    a.href = url;
    var event = new MouseEvent('click');
    // 指定下载图片的名称
    a.download = (new Date()).getTime() + ".jpg";
    a.dispatchEvent(event);
}
2、走html2canvas
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

var dom = document.getElementById('map')
const exportOptions = {
  // 允许跨域
  useCORS: true,
  // 忽略不输出
  ignoreElements: function (element) {
    const className = element.className || '';
    return !(
      className.indexOf('ol-control') === -1 ||
      className.indexOf('ol-scale') > -1 ||
      (className.indexOf('ol-attribution') > -1 &&
        className.indexOf('ol-uncollapsible'))
    );
  },
};
html2canvas(dom, exportOptions).then(function (canvas) {
 var url = canvas.toDataURL("image/jpeg");
 console.log(url);
 var a = document.createElement('a');
 var event = new MouseEvent('click');
 // 指定下载图片的名称
 a.download = (new Date()).getTime() + ".jpg";
 a.href = url;
 // 触发超链接的点击事件
 a.dispatchEvent(event);
})
3、几个需要注意点: 3.1、注意     加载的地图需要允许跨域 (source里面配置 crossOrigin:'anonymous',),是否地图打印不出来,空白的     这是因为canvas的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. canvas被污染了导致的! 3.2、转pdf
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script>

 //这一段添加到canvas后面
 const pdf = new jspdf.jsPDF('landscape', undefined, "A4");
 pdf.addImage(
 canvas.toDataURL('image/jpeg'),
    'JPEG',
    0,
    0,
    0,//dim[0],
    0//dim[1]
    );
 pdf.save('map.pdf');

标签:canvas,随手,打印输出,openlayer,url,className,var,new,event
来源: https://www.cnblogs.com/whaleX/p/16598856.html