65.9K
CodeProject is changing. Read more.
Home

Export Chart.js Charts as Image

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (8 votes)

Aug 23, 2016

CPOL
viewsIcon

70766

downloadIcon

1901

Easily export chart.js charts in image formats

Introduction

Chart.js is a widely used plugin for building charts. As it is open source and has a nice look and feel, it is a very best option for some paid chart plugins. While I was working with chart.js, I was at a situation where I wanted to export chart in Image format. Normally, Chart.js does not having any default option for Exporting in Image format. But as chart.js uses canvas to build chart in HTML, we can simply use canvas for exporting chart.

Using the Code

First, build your chart with your chart data using chart.js.

//
// var ctx = document.getElementById("myChart").getContext("2d");
// var myNewChart = new Chart(ctx).Pie(data, options);
//

Chart.js uses canvas to build charts in HTML. We can convert that canvas using toDataUrl method of jquery to base64 string.

//
// var url_base64jp = document.getElementById("myChart").toDataURL("image/jpg");
//

Add one anchor tag in your HTML.

//
// <a id="link2" download="ChartJpg.jpg">Save as jpg</a>
//

Set that converted base64 string as a href for a anchor tag. 

//
// link1.href = url_base64;
//

It's done.

Simply click on your link (in anchor tag) to export chart.

You can refer to the sample example in the attached files.