VOOZH about

URL: https://www.geeksforgeeks.org/javascript/how-to-converte-chartjs-canvas-chart-to-image-using-todataurl-results-in-blank-image/

⇱ How to Converte Chart.js Canvas Chart to Image using .toDataUrl() Results in Blank Image? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Converte Chart.js Canvas Chart to Image using .toDataUrl() Results in Blank Image?

Last Updated : 28 Aug, 2024

In Chart.js, we can convert the canvas chart into an image using the .toDataURL() method, which generates a base64-encoded data URL representing the chart. This allows us to save or display the chart as an image.

These are the following approaches:

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>

Basic Conversion to Image

In this approach, we are using Chart.js to create a bar chart that is displayed alongside a button. When the button is clicked, the chart is converted to an image using the toDataURL() method, which generates a base64-encoded image from the chart's canvas element. This image is then displayed in an <img> tag beside the chart.

Example: The below example performs Basic Conversion to Image.

Output:

Advanced Conversion with Custom Image Styling

In this approach, we are enhancing the conversion of a Chart.js canvas chart to an image by applying advanced styling and layout adjustments. The .toDataURL() method is used to convert the chart into a base64-encoded image, which is then displayed within a styled container with custom borders, shadows, and hover effects.

Example: The below example performs Advanced Conversion with Custom Image Styling.

Output:

Comment
Article Tags: