如何使用reactjs在chart.js中的甜甜圈图上显示车速表 [英] how to show speedometer on Doughnut chart in chart.js using reactjs

查看:50
本文介绍了如何使用reactjs在chart.js中的甜甜圈图上显示车速表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个半甜甜圈图,想要显示为速度计,但无法显示.按照此代码段

I've created a half doughnut chart and wanted to show like a speedometer, but couldn't able to make it. as per this snippet

这是我的代码:

import React, { Component } from "react";
import { Doughnut } from "react-chartjs-2";
import Data from "./Data.json";
const data = {
  // labels: ["Red", "Green", "Yellow"],
  datasets: [
    {
      data: [500, 500, 500],
      backgroundColor: ["red", "#FFCE56", "lightgreen"],
      hoverBackgroundColor: ["red", "#FFCE56", "lightgreen"]
    }
  ],
  options: {
    rotation: 1 * Math.PI,
    circumference: 1 * Math.PI,
    legend: {
      display: false
    },
    tooltip: {
      enabled: false
    },
    cutoutPercentage: 70
  }
};

export default class DonutChart extends Component {
  render() {
    return (
      <div>
        <h2>Sample</h2>
        <Doughnut height="100px" data={data} options={data.options} />
      </div>
    );
  }
}

此处是示例代码

有人可以在此查询中帮助我以这种格式实现吗?

Can anyone help me in this query to achieve in this format?

推荐答案

基于 Konstantin S. 的nofollow noreferrer>代码示例,您可以

Base on the code sample from Konstantin S., you could register a plugin globally inside the componentDidMount() method and implement an afterDraw function as follows:

componentDidMount() {
  Chart.pluginService.register({
    afterDraw: chart => {
      var needleValue = chart.chart.config.data.datasets[0].needleValue;
      var dataTotal = chart.chart.config.data.datasets[0].data.reduce((a, b) => a + b, 0);
      var angle = Math.PI + (1 / dataTotal * needleValue * Math.PI);
      var ctx = chart.chart.ctx;
      var cw = chart.chart.canvas.offsetWidth;
      var ch = chart.chart.canvas.offsetHeight;
      var cx = cw / 2;
      var cy = ch - 6;

      ctx.translate(cx, cy);
      ctx.rotate(angle);
      ctx.beginPath();
      ctx.moveTo(0, -3);
      ctx.lineTo(ch - 10, 0);
      ctx.lineTo(0, 3);
      ctx.fillStyle = 'rgb(0, 0, 0)';
      ctx.fill();
      ctx.rotate(-angle);
      ctx.translate(-cx, -cy);
      ctx.beginPath();
      ctx.arc(cx, cy, 5, 0, Math.PI * 2);
      ctx.fill();
    }
  });
}

这希望在数据集中定义属性 needleValue .

This expects the property needleValue to be defined inside the dataset.

datasets: [{
  data: [500, 500, 500],
  needleValue: 580,
  ...
}],

请查看修改后的 CodeSandbox

Please have a look at your amended CodeSandbox

这篇关于如何使用reactjs在chart.js中的甜甜圈图上显示车速表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆