Angular中文博客

分享让你更聪明

Angular中使用html2canvas导出截图

浏览:168次 评论:0次 日期:2024年08月06日 11:50:27 作者:管理员

Angular中使用html2canvas导出截图

# 安装html2canvas
npm i html2canvas
<main #canvasBox>
    <!-- 这里的内容会被制作成图片下载 -->
</main>

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

TypeScript代码

@ViewChild('canvasBox') canvasBox!: ElementRef;
@ViewChild('canvas') canvas!: ElementRef;
@ViewChild('downloadLink') downloadLink!: ElementRef;

downloadImage() {
    // @ts-ignore
    html2canvas(this.canvasBox.nativeElement).then((canvas: any) => {
        console.log(canvas.toDataURL());
        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();
    });
}

发表评论