Click here to Skip to main content
15,887,027 members
Articles / Web Development / HTML5
Tip/Trick

Export Chart.js Charts as Image

,
Rate me:
Please Sign up or sign in to vote.
4.47/5 (8 votes)
23 Aug 2016CPOL 69.9K   1.9K   6   4
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)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExport chart to png Pin
Mahlatse Leshiba24-Aug-20 22:32
Mahlatse Leshiba24-Aug-20 22:32 
PraiseThanks! Pin
Member 141084034-Jan-19 11:27
Member 141084034-Jan-19 11:27 
QuestionIt was very useful Pin
Hitesh Trivedi24-Aug-16 2:08
Hitesh Trivedi24-Aug-16 2:08 
Praisevery useful Pin
Member 1270046323-Aug-16 20:49
Member 1270046323-Aug-16 20:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.