Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML5

Export Chart.js Charts as Image

4.47/5 (8 votes)
23 Aug 2016CPOL 70.8K   1.9K  
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.

C++
//
// 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.

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

Add one anchor tag in your HTML.

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

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

C++
//
// 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)