Chartjs-How to use ChartJS toBase64Image in Vue?

0👍

You need to set a ref on the component like this;

Template;

<Chart
    ref="myChart"
    ...
/>

<script setup>;

import { ref } from "vue";

...

const myChart = ref();

...

onComplete: () => {
    var base64Chart = myChart.value.toBase64Image();
}

0👍

You get a context object in the onComplete this animation object has the chart instance on which you can call the toBase64Image method.

    onComplete: (ctx) => {
     // how to get the Chart constructor here?
      var base64Chart = ctx.chart.toBase64Image();
    }
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3]
    }]
  },
  options: {
    animation: {
      onComplete: (ctx) => {
        console.log(ctx.chart.toBase64Image());
      }
    }
  }
});
<script src="https://npmcdn.com/chart.js@4.2.0/dist/chart.umd.js"></script>
<div class="myChartDiv">
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

Leave a comment