在leaflet和openlayers中并没有提供地图导出图片或pdf的方法,如果需要导出地图的内容,一般都是使用 HTMLCanvasElement.toBlob() 的方法,把地图内容导出成为一个图片类型的Blob对象了(替换了原先非标准的mozGetAsFile方法).toBlob方法是异步的:
void canvas.toBlob(callback, mimeType, qualityArgument);
默认的图片输出格式是PNG格式,同样可以指定保存为其他格式,还可以指定图像保存的压缩质量:
canvas.toBlob(function(blob){…}, “image/jpeg”, 0.95); // 用95%质量的JPEG格式保存
导出图片方法
把画布图形保存为png格式文件并添加到页面
1 2 3 4 5 6 7 8 9 10 11 12
| var canvas = document.getElementById("canvas"); canvas.toBlob(function(blob) { var newImg = document.createElement("img"),url = URL.createObjectURL(blob); newImg.onload = function() { // no longer need to read the blob so it's revoked URL.revokeObjectURL(url); }; newImg.src = url; document.body.appendChild(newImg); });
|
利用FileSaver可以把画布图形保存为png格式文件并下载
1 2 3 4
| var canvas = document.getElementById("canvas"); canvas.toBlob(function(blob) { saveAs(blob, 'map.png'); });
|
把画布图形保存为icon格式文件并添加下载链接(只支持Mozilla)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| var canvas = document.getElementById("canvas"); var d = canvas.width; ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(d / 2, 0); ctx.lineTo(d, d); ctx.lineTo(0, d); ctx.closePath(); ctx.fillStyle = "yellow"; ctx.fill(); function blobCallback(iconName) { return function(b) { var a = document.createElement("a"); a.textContent = "Download"; document.body.appendChild(a); a.style.display = "block"; a.download = iconName + ".ico"; a.href = window.URL.createObjectURL(b); } } canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon','-moz-parse-options:format=bmp;bpp=32');
|
转换为pdf方法
利用jsPDF输出pdf文件
1 2 3 4 5 6 7 8 9 10
| objImageData = canvas.toDataURL("image/jpeg"); fileName = fileName + ".pdf"; var doc = new jsPDF(); var pagewidth = canvas.width / 3; var pageheight = canvas.height / 3; doc.addPage(pagewidth + 20, pageheight + 20); doc.deletePage(1); doc.addImage(objImageData, 'JPEG', 10, 10, pagewidth, pageheight); doc.save(fileName);
|
跨域的处理
HTMLCanvasElement.toBlob()、HTMLCanvasElement.toDataURL()等方法在地图有跨域图片的情况下无法使用,浏览器会以不安全的访问来拒绝生成跨域图片的二进制对象或URL。