Answer a question

I would like to add text inside the chart of Doughnut type.
I'm using this plugin in my vuejs project: https://github.com/apertureless/vue-chartjs
Currently, It's showing for all charts. I just want to have only Doughnut chart, but it's show all chart.

//*** 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 ***//

enter image description here

Thank you and appreciate.

Answers

Rather than install the plugin globally with Chart.pluginService.register you can load it in your mounted hook of that specific chart with this.addPlugin:

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

working example

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐