如何在Vue中使用ChartJS toBase64Image?

rkttyhzu  于 2023-02-04  发布在  Chart.js
关注(0)|答案(2)|浏览(136)

我使用的是基于ChartJS的Primevue图表组件。
设置几乎相同。
文档显示我必须请求一个新的Chart(),然后调用toBase 64 Image();

问题是我不知道如何获取 Chart 构造函数

<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 class="config-asset-chart">
    <span>{{title}}</span>
    <Chart
      class="px-2"
      :data="data"
      :width="props.printWidth"
      :height="props.printHeight"
      :options="options"
      :plugins="[ChartDataLabels]"
    />
  </section>
</template>
kcwpcxri

kcwpcxri1#

您需要像这样在组件上设置一个ref;
模板;

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

<script setup> ;

import { ref } from "vue";

...

const myChart = ref();

...

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

xwmevbvl2#

onComplete中得到一个context对象,这个animation对象有一个chart示例,可以在这个示例上调用toBase64Image方法。

onComplete: (ctx) => {
     // how to get the Chart constructor here?
      var base64Chart = ctx.chart.toBase64Image();
    }

x一个一个一个一个x一个一个二个x

相关问题