How to Download Canvas as Image on Button Click in ChartJS?
Last Updated :
30 Aug, 2024
In Chart.js, the charts that are generated can be converted and downloaded as images for easy sharing and reporting. By using built-in methods like toBase64Image() and the HTML canvas toBlob() method, we can enable users to download charts in formats such as PNG. These techniques provide a simple way to capture the visual data from charts and offer a convenient option for exporting and saving graphical content directly from the browser.
Below are the two approaches to downloading Canvas as an Image on Button Click in Chart JS:
ChartJS CDN Link
You need to add the below link to your HTML document to use Chart.js.
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
Using toBase64Image() function
In this approach, we are using the toBase64Image() function from Chart.js to convert the pie chart into a base64-encoded image. The button click event creates a temporary anchor element with the href set to the base64 image data, allowing the user to download the chart as a PNG file named pie_chart.png.
Example: The below example uses toBase64Image() function to Download Canvas as Image on Button Click in Chart JS.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Using to Base64Image() function </title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
h1 {
color: green;
}
h3 {
margin-top: 0;
}
canvas {
max-width: 100%;
height: auto;
}
.container {
max-width: 400px;
margin: 0 auto;
}
.chart-container {
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
}
.button-container {
text-align: center;
margin-top: 10px;
}
.button-container button {
padding: 10px 20px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h1>GeeksforGeeks</h1>
<h3>Using toBase64Image() function</h3>
<div class="chart-container">
<canvas id="myPieChart"></canvas>
</div>
<div class="button-container">
<button id="downloadBtn">
Download as Image
</button>
</div>
</div>
<script src=
"https://cdn.jsdelivr.net/npm/chart.js">
</script>
<script>
// Initialize Chart.js Pie Chart
const ctx = document.getElementById('myPieChart')
.getContext('2d');
const myPieChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'GeeksforGeeks Data',
data: [10, 20, 30],
backgroundColor: ['red', 'blue', 'yellow'],
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
// Download button functionality
document.getElementById('downloadBtn')
.addEventListener('click', () => {
const image = myPieChart
.toBase64Image();
const link = document
.createElement('a');
link.href = image;
link.download = 'pie_chart.png';
link.click();
});
</script>
</body>
</html>
Output:
Using HTML Canvas toBlob() Method
In this approach, we are using the HTML Canvas toBlob() method to convert the chart's canvas to a Blob object, which represents the image data. This Blob is then converted to a URL using URL.createObjectURL(), allowing us to create a download link for the image. Clicking the button triggers this link, enabling the download of the chart as a PNG file.
Example: The below example uses HTML Canvas toBlob() Method to Download Canvas as Image on Button Click in Chart JS.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Using HTML Canvas toBlob() Method </title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
h1 {
color: green;
}
h3 {
margin-top: 0;
}
canvas {
max-width: 100%;
height: auto;
}
.container {
max-width: 400px;
margin: 0 auto;
}
.chart-container {
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
}
.button-container {
text-align: center;
margin-top: 10px;
}
.button-container button {
padding: 10px 20px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h1>GeeksforGeeks</h1>
<h3>Using HTML
Canvas `toBlob()` Method
</h3>
<div class="chart-container">
<canvas id="myBarChart"></canvas>
</div>
<div class="button-container">
<button id="downloadBtn">Download
as Image
</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js">
</script>
<script>
// Initialize Chart.js Bar Chart
const ctx = document
.getElementById('myBarChart')
.getContext('2d');
const myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['HTML', 'CSS', 'JavaScript', 'Python'],
datasets: [{
label: 'GeeksforGeeks Tutorials',
data: [30, 50, 70, 40],
backgroundColor: ['red', 'blue', 'green', 'purple']
}]
},
options: {
responsive: true,
maintainAspectRatio: false
}
});
// Download button functionality using Canvas toBlob() method
document.getElementById('downloadBtn')
.addEventListener('click', () => {
const canvas = document
.getElementById('myBarChart');
canvas.toBlob((blob) => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'bar_chart.png';
link.click();
});
});
</script>
</body>
</html>
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read