【问题标题】:vue-chartjs - Doughnut chart with text in the middlevue-chartjs - 中间有文字的圆环图
【发布时间】:2020-03-30 10:35:12
【问题描述】:


我想在甜甜圈类型的图表中添加文本。
我在我的 vuejs 项目中使用这个插件:https://github.com/apertureless/vue-chartjs
目前,它显示在所有图表中。 我只想有甜甜圈图表,但它显示所有图表。

//*** Doughnut chat ***//

import { Doughnut } from "vue-chartjs";
import Chart from "chart.js";

export default {
extends: Doughnut,
  data: () => ({
  chartdata: {
  labels: ["Cambodia", "Thailand", "Vietnam", "Laos"],
  datasets: [
    {
      label: "Data One",
      backgroundColor: ["#a3c7c9", "#889d9e", "#647678", "f87979"],
      data: [91, 3, 3, 3]
      }
     ]
     },
  options: {
    legend: {
      display: false
    },
    responsive: true,
    maintainAspectRatio: false
  }
}),

mounted() {
  this.renderChart(this.chartdata, this.options);
  this.textCenter(880);
},
methods: {
  textCenter(val) {
    Chart.pluginService.register({
      beforeDraw: function(chart) {
        var width = chart.chart.width;
        var height = chart.chart.height;
        var ctx = chart.chart.ctx;

        ctx.restore();
        var fontSize = (height / 114).toFixed(2);
        ctx.font = fontSize + "em sans-serif";
        ctx.textBaseline = "middle";

        var text = val;
        var textX = Math.round((width - ctx.measureText(text).width) / 2);
        var textY = height / 2;

         ctx.fillText(text, textX, textY);
         ctx.save();
       }
     });

     Chart.plugins.unregister(this.chartdata);
   }
 }};
 //*** end Doughnut chat ***//

谢谢你,感激不尽。

【问题讨论】:

    标签: vue.js vue-chartjs


    【解决方案1】:

    您可以使用Chart.pluginService.register 将其加载到特定图表的挂载钩子中,而不是使用this.addPlugin 全局安装插件:

    mounted() {
      this.addPlugin({
        id: 'my-plugin',
        beforeDraw: function(chart) {}
      })
      this.renderChart(this.chartdata, this.options);
    },
    

    working example

    【讨论】:

    • 您好,我正在尝试让它在我的 vue3 项目中工作,但我收到了 addPlugin is not defined 错误。 addPlugin 来自哪里?
    • @LovelyAndy 我还没有在 vue3 中尝试过,但在上面的示例中,它是由正在扩展的 vuechart 组件定义的。如果您点击上面示例的链接,您会看到该组件包含:extends: VueChartJs.Doughnut
    • 感谢您的回复!多亏了您在这里的评论,我想我现在有了一个很好的工作版本。干得好,你帮我减轻了很多压力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多