如何在Vue中使用ChartJS toBase64Image?

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

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

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

  1. <script lang="ts" setup>
  2. import Chart from 'primevue/chart';
  3. import ChartDataLabels from 'chartjs-plugin-datalabels';
  4. import { ref } from 'vue';
  5. import { ChartData } from 'chart.js';
  6. const props = defineProps<{
  7. data?: ChartData;
  8. aspectRatio?: number;
  9. title?: string;
  10. printWidth?: number;
  11. printHeight?: number;
  12. }>();
  13. const options = ref({
  14. plugins: {
  15. datalabels: {
  16. labels: {
  17. title: {
  18. color: 'black',
  19. },
  20. },
  21. align: 'end',
  22. anchor: 'start',
  23. offset: 1,
  24. formatter
  25. }
  26. },
  27. aspectRatio: props.aspectRatio
  28. animation: {
  29. onComplete: () => {
  30. // how to get the Chart constructor here?
  31. var base64Chart = Chart.toBase64Image();
  32. }
  33. }
  34. });
  35. </script>
  36. <template>
  37. <section class="config-asset-chart">
  38. <span>{{title}}</span>
  39. <Chart
  40. class="px-2"
  41. :data="data"
  42. :width="props.printWidth"
  43. :height="props.printHeight"
  44. :options="options"
  45. :plugins="[ChartDataLabels]"
  46. />
  47. </section>
  48. </template>
kcwpcxri

kcwpcxri1#

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

  1. <Chart
  2. ref="myChart"
  3. ...
  4. />

<script setup> ;

  1. import { ref } from "vue";
  2. ...
  3. const myChart = ref();
  4. ...
  5. onComplete: () => {
  6. var base64Chart = myChart.value.toBase64Image();
  7. }
展开查看全部
xwmevbvl

xwmevbvl2#

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

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

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

相关问题