DEV Community

Cover image for How to save chart as image Chart.js
Noé Melo Locumber
Noé Melo Locumber

Posted on

8 3

How to save chart as image Chart.js

HTML code:



<!-- Chart.js Object -->
<canvas id="lineChart" width="300" height="150"> </canvas>

<!-- Download Button
"download" attribute is very important:
<a download ="nameChart.jpg"></a> 
-->
<a id="download"
        download="ChartImage.jpg" 
        href=""
        class="btn btn-primary float-right bg-flat-color-1"
        title="Descargar Gráfico">

        <!-- Download Icon -->
 <i class="fa fa-download"></i>
 </a>


Enter fullscreen mode Exit fullscreen mode

JavaScript code:



//Download Chart Image
document.getElementById("download").addEventListener('click', function(){
  /*Get image of canvas element*/
  var url_base64jp = document.getElementById("lineChart").toDataURL("image/jpg");
  /*get download button (tag: <a></a>) */
  var a =  document.getElementById("download");
  /*insert chart image url to download button (tag: <a></a>) */
  a.href = url_base64jp;
});


Enter fullscreen mode Exit fullscreen mode

Example of Line Chart:

Alt Text

Full code in GitHub:

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (1)

Collapse
 
laviku profile image
Lavinia

Great! Thanks for sharing!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay