从角度为2

时间:2017-05-14 03:35:35

标签: angular html2canvas

我在角度2中使用html2canvas来捕获网页但我需要使用webapi post call将字符串图像发送到服务器端

imageDownload() {
    html2canvas(document.body).then(function (canvas) {
        var imgData = canvas.toDataURL("image/png");
        document.body.appendChild(canvas);
    });
}

我无法从html2canvas访问此打字稿函数,如何访问此方法将图像字符串发送到服务器端

AddImagesResource(image: any) {
    this.imagesService.addCanvasResource(image)
        .subscribe(response => {
            this.eventsEmitter.broadcast('Success', 'Changes Saved Succesfully');
        },
        error => {
            this.eventsEmitter.broadcast('Error', 'Error Occured');
        });
}

3 个答案:

答案 0 :(得分:4)

在Package.json中添加

"dependencies": {
"html2canvas": "0.5.0-beta4",
"@types/html2canvas": "0.5.32"
.......
}

运行npm install。

您可能会遇到与找不到或未定义的html2canvas相关的错误。 用systemjs来解决这个问题:

   map: {

  // angular bundles
  '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
  ...............

  // other libraries
  'rxjs': 'npm:rxjs',
  'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
  'html2canvas': 'npm:html2canvas' //for html canvas
 }
packages: {
  .................
   rxjs: {
     defaultExtension: 'js'
   },
   html2canvas: {
     main:'./dist/html2canvas.js',
     defaultExtension: 'js'
   }
 }

现在您将获得html2canvas的完整参考。

我已经将imagedata创建为图像的dataURI和Blob对象。

HTML:

 <div class="container" #container>    
   <img id="imgtag" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTexytN9PLhK7bFL-OofVQ9EYmXNhrZP9plY-_L6lKoycVmcjVw"
    alt="Smiley face" height="420" width="420">
   <div style="margin-top:20px;margin-left:20px">
    <button type="button" class="btn btn-secondary" (click)=snapShot()>Snap Shot</button>
   </div>
</div>

TypeScript代码:

 import { Component, ViewChild, ElementRef } from '@angular/core';
 import * as html2canvas from 'html2canvas';
 export class AppComponent {
 @ViewChild('container') container: ElementRef;
 snapShot() {
     let dataURI = this.createThumbnail(this.container.nativeElement);
 }

createThumbnail(blockelement: any) {
let element = blockelement.querySelector('#imgtag');
console.log(element, 'element')
if (element !== null && element !== undefined) {
  html2canvas(element).then(function (canvas: any) {
    let dataURI = canvas.toDataURL();
    console.log('img', dataURI);

    let blobObject = this.dataURItoBlob(dataURI);
    console.log('img', blobObject);
    //this.AddImagesResource(blobObject) your case
    //AddImagesResource will call the service method which can
    //post this blob object as multipart file
    //this formdata and httppost call should in service layer,in your case its imagesService.
    /*
      let formData = new FormData();
      formData.append('file', blobObject);
      console.log(formData, 'formData');
      return this.http.post(API_URL.saveThumbnailURL, formData).map((res: Response) => {
      console.log(res);
      return res.json();
    })        */
     }.bind(this));
   }
 }
  dataURItoBlob(dataURI: string) {
  let byteString: any;
  if (dataURI.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(dataURI.split(',')[1]);
  else
    byteString = decodeURI(dataURI.split(',')[1]);

  // separate out the mime component
  let mimeString: any = dataURI.split(',')[0].split(':')[1].split(';')[0];

  // write the bytes of the string to a typed array
  let blob: any = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    blob[i] = byteString.charCodeAt(i);
  }
  return new Blob([blob], {
    type: mimeString
  });
}
}

您可以使用formdata将此stringdata / blob对象作为multipart文件发送到服务器。

希望这会有所帮助

答案 1 :(得分:0)

您可以在元素上使用(单击)事件并将功能分配给它,

 <button  (click)="AddImagesResource(img)"></button>

如果你需要调用ts中的函数,你可以这样做,

this.AddImagesResource(imgData);

答案 2 :(得分:0)

这是角度应用程序中[1/k,1.1/k,2,3,10]实际上的用途,您可以明确地使用它来调用角度应用程序。因此,在您的组件中,您将执行与此类似的操作:

renderListItems(items){
        return(
            <div>
            {items.map(obj =>
                <div key={obj._id} className="panel-body panel-row">
                    <div  className="row">
                        <div className="col-md-12">
                            <h2 className="title">{obj.display_name}</h2>
                            <p className="edited">Last edited on {moment(obj.updated_at).format('DD MMM YYYY')}</p>
                            <div className="actions_wrap">
                                <Link to={`/mall-promospace/edit/${obj._id}`}>Edit</Link>
                                <a onClick={()=> this.setState({openConfirmationModal:true, selectedItemId: obj._id, selectedItemName: obj.display_name})}>Delete</a>
                            </div>
                        </div>
                    </div>
                </div>
            )}
            </div>
        )
    }

然后从html2canvas中你可以按照你的预期调用Zone.js,ngZone应该把它放在正确的上下文中。

修改 我创建了一个plunker,说明如何使用按钮单击和普通的旧JavaScript代码来完成它。

https://embed.plnkr.co/erIdbP/