首页 > 解决方案 > 如何将div转换为图像?

问题描述

我有一个 div,我需要制作这个 div 的图像并发送到服务器。有没有办法使用Angular 7来做到这一点?我试图搜索库但没有结果。所有解决方法都使用本机 JS。

标签: angular

解决方案


要将 HTML 内容保存到图像中,您需要使用HTML2CANVAS

创建一些参考孩子

@ViewChild('screen') screen: ElementRef; @ViewChild('canvas') canvas: ElementRef; @ViewChild('downloadLink') downloadLink: ElementRef;

当然,您需要添加 HTML 引用,例如

<table #screen id="table" class="table table-striped">...

<div id="download">
  <img #canvas>
  <a #downloadLink></a>
</div>

然后创建一个函数来制作图像

downloadImage(){

html2canvas(this.screen.nativeElement).then(canvas => {
      this.canvas.nativeElement.src = canvas.toDataURL();
      this.downloadLink.nativeElement.href = canvas.toDataURL('image/png');
      this.downloadLink.nativeElement.download = 'marble-diagram.png';
      this.downloadLink.nativeElement.click();
});

}

工作堆栈闪电战


推荐阅读