ChartJS 通过从圆环图提取百分比数据在HTML标记上显示百分比

ha5z0ras  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(176)

我是JavaScript新手,我很想知道如何通过JS从圆环图中获取百分比数据,以百分比的形式显示数据

<div class="block-text">
             <div class="flex-chart"> <div class="box-file"></div><p class="spacing">abc</p>
             <p id = "count">20%</p></div>

             <div class="flex-chart"> <div class="box-url"></div><p class="spacing">xyz</p> 
             <p>30%</p>

         </div>
         </div>

以下是圆环图JS代码:

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>  -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>

<script>
// setup 
const data = {
  //labels: ['xyz', 'abc'],
  datasets: [{
   // label: 'Weekly Sales',
    data: [12, 20],     
    backgroundColor: [
      'rgb(254, 214, 10)',
      'rgb(255, 90, 48)'

    ],
    borderColor: [
      "#ffffff",         
    ],
    borderWidth: 1
  }]
};

// config 
const config = {
  type: 'doughnut',
  data,
 options: {
 plugins: {
  datalabels: {

    formatter: (value, ctx) => {

      let datasets = ctx.chart.data.datasets;

      if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
       var sum = datasets[0].data.reduce((a, b) => a + b, 0);
       var percentage = Math.round((value / sum) * 100) + '%';
      return percentage;

     } else {
       return percentage;

     }
   },
   color: '#fff',
 }
}        
}
}

// render init block
const myChart = new Chart(
  document.getElementById('chart'),
  config
);

现在我想显示百分比,以便从圆环图百分比变量中获取它,并将其发布到“abc”标记abc上
百分之二十

我希望用百分比数据替换20%,因为20%此时是静态的

6gpjuf90

6gpjuf901#

检查此代码可能会对您有所帮助。

var data = [{
   data: [50, 55, 60, 33],
   labels: ["India", "China", "US", "Canada"],
   backgroundColor: [
     "#4b77a9",
     "#5f255f",
     "#d21243",
     "#B27200"
   ],
   borderColor: "#fff"
 }];

 var options = {
   tooltips: {
     enabled: false
   },
   plugins: {
     datalabels: {
       formatter: (value, ctx) => {

         let datasets = ctx.chart.data.datasets;

         if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
           let sum = datasets[0].data.reduce((a, b) => a + b, 0);
           let percentage = Math.round((value / sum) * 100) + '%';
           return percentage;
         } else {
           return percentage;
         }
       },
       color: '#fff',
     }
   }
 };

 var ctx = document.getElementById("pie-chart").getContext('2d');
 var myChart = new Chart(ctx, {
   type: 'pie',
   data: {
     datasets: data
   },
   options: options
 });

JSFIDDLE

相关问题