Home > Net >  How to use ChartJS toBase64Image in Vue?
How to use ChartJS toBase64Image in Vue?

Time:02-01

I am using primevue chart component, which is base on ChartJS.

the setting is almost the same.

docs showing I have to asgin a new Chart() then call toBase64Image();

enter image description here

the question is, I don't know how to get the Chart constructor?

<script lang="ts" setup>
import Chart from 'primevue/chart';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { ref } from 'vue';
import { ChartData } from 'chart.js';

const props = defineProps<{
  data?: ChartData;
  aspectRatio?: number;
  title?: string;
  printWidth?: number;
  printHeight?: number;
}>();

const options = ref({
  plugins: {
    datalabels: {
      labels: {
        title: {
          color: 'black',
        },
      },
      align: 'end',
      anchor: 'start',
      offset: 1,
      formatter
    }
  },
  aspectRatio: props.aspectRatio
  animation: {
    onComplete: () => {
     // how to get the Chart constructor here?
      var base64Chart = Chart.toBase64Image();
    }
  }
});

</script>

<template>
  <section >
    <span>{{title}}</span>
    <Chart
      
      :data="data"
      :width="props.printWidth"
      :height="props.printHeight"
      :options="options"
      :plugins="[ChartDataLabels]"
    />
  </section>
</template>

CodePudding user response:

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();
}

CodePudding user response:

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/[email protected]/dist/chart.umd.js"></script>
<div >
  <canvas id="myChart" width="600" height="400"></canvas>
</div>

  • Related