拍摄包含gmap的div时,html2canvas无法正常工作(Google Map)

时间:2017-06-08 11:45:03

标签: javascript image angular canvas html2canvas

我正在将包含谷歌地图的div转换为图片,但它没有按原样显示。

我正在使用angular4。

我的原始图像如下:

original div

但用html2canvas转换后显示如下:

enter image description here

我的转换代码如下:

html2Cnv(){
    let self = this;
    let mycnvHtml: HTMLVideoElement = self.mycnvHtml.nativeElement;
    html2canvas(mycnvHtml, {
      onrendered: function(canvas1) {
        canvas1.toBlob((blob: Blob)=>{
          let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', {
            type: 'image/png'
          });
          self.fileShare.addFile(file);
          self.onDone.emit(file);
        }, "image/png");
      }
    });
  }

1 个答案:

答案 0 :(得分:0)

代替将包含谷歌地图的div转换为画布,我按照以下步骤进行操作,并且我达到了我的要求,但它没有给出路线

  

原始div enter image description here   转换后enter image description here

  1. 获取地图网址

    getCordDistance() { let radlat1 = Math.PI * this.locStart.lat/180; let radlat2 = Math.PI * this.locEnd.lat/180; let theta = this.locStart.lng-this.locEnd.lng; let radtheta = Math.PI * theta/180; let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); dist = Math.acos(dist); dist = dist * 180/Math.PI; dist = dist * 60 * 1.1515; /*if (unit=="K") { dist = dist * 1.609344 } if (unit=="N") { dist = dist * 0.8684 }*/ return dist }

    getImgUrl(cll){ let dist=this.getCordDistance(); let comn={ lat:((this.locStart.lat+this.locEnd.lat)/2), lng:((this.locStart.lng+this.locEnd.lng)/2) }; try { let ppp=document.getElementById('map456'); this.dynamicImg='https://maps.googleapis.com/maps/api/staticmap?' + 'center=' +comn.lat+','+comn.lng + '&zoom='+(dist<1?15:dist>1800?3:dist>900?4:this.mapRef.getZoom())+ '&size='+ppp.offsetWidth+'x'+ppp.offsetHeight + '&maptype=roadmap'+ '&markers=color:blue%7Clabel:S%7C'+this.locStart.lat+','+this.locStart.lng + '&markers=color:red%7Clabel:C%7C'+this.locEnd.lat+','+this.locEnd.lng + '&key=myKey'; }catch(er){console.log(er)} if(cll){ cll() } }

  2. 如果您只需要地图图片

    ,请执行ajax请求以获取图像blob

    html2Cnv(){ let self = this; this.getImgUrl(()=>{ let oReq = new XMLHttpRequest(); oReq.open("GET", this.dynamicImg, true); oReq.responseType = "arraybuffer"; oReq.onload =(oEvent)=>{ let blob = new Blob([oReq.response], {type: "image/png"}); let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', { type: 'image/png' }); self.fileShare.addFile(file); self.onDone.emit(file); }; oReq.send(); }); }

  3. 否则创建一个与我们要截取的div相同的重复内容,但是代替google map创建一个带有src的img标签,如第一步所示

    html2Cnv(){ let self = this; this.getImgUrl(()=>{ html2canvas(this.canvas1, { onrendered: function(canvas1) { canvas1.toBlob((blob: Blob)=>{ let file = new File([blob], 'msr-' + (new Date).toISOString().replace(/:|\./g, '-') + '.webm', { type: 'image/png' }); self.fileShare.addFile(file); self.onDone.emit(file); }, "image/png"); } }); }) }