简体   繁体   中英

vue-chartjs - Doughnut chart with text in the middle


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

在此处输入图像描述

Thank you and appreciate.

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

If you have a 'tall' legend group (or not), you would like to set the text just in the middle of doughnut, not the canvas itself. So I recommend to change some vars to point to chartArea (the doughnut itself):

const width = chart.chartArea.width;
const height = chart.chartArea.height;
//...
const textY = chart.chartArea.top + height / 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM