2

我想创建一个链接以允许用户下载显示的图表。我目前试图让它工作的方式是.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>

组件

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

  exportGraph(){
    this.downloadLink = this.export_graph.toDataURL("image/png");
  }

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

4

1 回答 1

10

您应该使用锚标记<a>而不是<button>,您可以将其设置为看起来像一个按钮。然后你可以附加一个点击事件并这样做:

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";
}

重要的是document.getElement...点击而不是事先进行。这样您就可以确定 html 视图 <canvas>已渲染并完成绘制(您可以在页面上看到它)。

你在你的问题中这样做的方式,你正在寻找<canvas>元素甚至在页面上呈现之前,这就是它未定义的原因。

于 2017-05-02T22:24:48.130 回答