将 ng2-chart canvas 导出为 png 图像
exporting ng2-chart canvas to png image
我想创建一个 link 以允许用户下载显示的图表。我目前试图让它工作的方式是 .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
您应该使用锚标记 <a>
而不是 <button>
,您可以将其设置为看起来像一个按钮。然后你可以附加一个点击事件并这样做:
笨蛋:http://plnkr.co/edit/xyfWok58R3eQdYk7pAds?p=preview
首先,将下载 link 添加到您的 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>
元素,甚至在它呈现在页面上之前,这就是它未定义的原因。
我想创建一个 link 以允许用户下载显示的图表。我目前试图让它工作的方式是 .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
您应该使用锚标记 <a>
而不是 <button>
,您可以将其设置为看起来像一个按钮。然后你可以附加一个点击事件并这样做:
笨蛋:http://plnkr.co/edit/xyfWok58R3eQdYk7pAds?p=preview
首先,将下载 link 添加到您的 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>
元素,甚至在它呈现在页面上之前,这就是它未定义的原因。