将ng2-chart画布导出为png图像

blu*_*arl 2 javascript ng2-charts angular

我想创建一个链接,允许用户下载显示的图形.我目前正试图让它发挥作用的方式是.toDataUrl被认为是一种安全的方式,还是有另一种方法可以实现这一目标.

HTML:

<canvas id="myChart" baseChart [colors]="colorsOverride" [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend"
    [chartType]="barChartType" (chartHover)="chartHovered($event)" (chartClick)="chartClicked($event)">
</canvas>

<div class="footer">
  <button (click)="exportGraph()">Export Graph</button>
</div>
Run Code Online (Sandbox Code Playgroud)

组件:

  export_graph = <HTMLCanvasElement>document.getElementById("myChart");
  downloadLink: string;

  exportGraph(){
    this.downloadLink = this.export_graph.toDataURL("image/png");
  }
Run Code Online (Sandbox Code Playgroud)

当我尝试导出时,这是我在控制台中收到的错误消息: Cannot read property 'toDataURL' of null

Ahm*_*lam 6

您应该使用锚标记<a>而不是<button>,您可以将其设置为看起来就像一个按钮.然后你可以附加一个click事件并以这种方式执行:

plunker:http://plnkr.co/edit/xyfWok58R3eQdYk7pAds?p =preview

首先,将下载链接添加到您的HTML <a href="#" (click)="downloadCanvas($event)"> DOWNLOAD THIS</a>

然后创建downloadCanvas功能

downloadCanvas(event) {
    // get the `<a>` element from click event
    var anchor = event.target;
    // get the canvas, I'm getting it by tag name, you can do by id
    // and set the href of the anchor to the canvas dataUrl
    anchor.href = document.getElementsByTagName('canvas')[0].toDataURL();
    // set the anchors 'download' attibute (name of the file to be downloaded)
    anchor.download = "test.png";
}
Run Code Online (Sandbox Code Playgroud)

重要的是做document.getElement...点击而不是事前.这样你就可以确定html视图并且 <canvas>已经渲染并完成绘图(你在页面上看到它).

你在问题中的方式,你正在寻找<canvas>元素甚至在页面上呈现,这就是为什么它是未定义的.