[英]ng2-chart with Angular 4: Can't bind to 'data' since it isn't a known property of 'canvas'
[英]exporting ng2-chart canvas to png image
我想創建一個鏈接,允許用戶下載顯示的圖形。 我目前試圖讓它工作的方式是.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>
,您可以將其設置為看起來就像一個按鈕。 然后你可以附加一個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";
}
在click上執行document.getElement...
非常重要,而不是在事前。 這樣你就可以確定html視圖和 <canvas>
已經渲染並完成繪圖(你在頁面上看到它)。
你在問題中這樣做的方式,你正在尋找<canvas>
元素甚至在頁面上呈現,這就是為什么它未定義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.