openlayers之地圖截圖 方法1 2

方法1

//this.map._this爲初始化地圖對象
     this.map._this.once('postcompose', function (event) {
          var canvas = event.context.canvas;
          if (navigator.msSaveBlob) {
            navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
          } else {
            canvas.toBlob(function (blob) {
              saveAs(blob, 'map.png');
            });
          }
        });
        this.map._this.renderSync();

方法2 調用html2canvas插件

// 調用html2canvas插件
 html2canvas(document.getElementById('map_container'), {
          allowTaint: false,
          foreignObjectRendering: true,
          taintTest: false,
          useCORS: true,//火狐瀏覽器添加項
          onrendered: function (canvas) {
            var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
            var userAgent = navigator.userAgent;
            //判斷是不是IE11
            if (-1 !== userAgent.indexOf("Trident")) {
              var arr = image.split(',');
              var mime = arr[0].match(/:(.*?);/)[1];
              var bstr = atob(arr[1]);
              var n = bstr.length;
              var u8arr = new Uint8Array(n);
              while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
              }
              window.navigator.msSaveBlob(new Blob([u8arr], { type: mime }), "download.png");
            } else {
              canvas.id = "mycanvas";
              //生成base64圖片數據
              var dataUrl = canvas.toDataURL();
              var newImg = document.createElement("img");
              newImg.setAttribute('crossOrigin', 'anonymous');
              newImg.src = dataUrl;
              var b = document.createElement('a')
              b.setAttribute("href", dataUrl)
              b.setAttribute("download", "img.png")
              document.body.appendChild(b)//火狐瀏覽器添加項
              b.click(); b.remove()
            }
          }
        });
相關文章
相關標籤/搜索