ChartJS 画布:“对象未定义”

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

我正在尝试在画布中创建一条线。一切都进行得很顺利,直到我在这一部分卡住了:

import { Doughnut } from "react-chartjs-2";
import "chart.js/auto";
import { Chart, ChartData, ChartDataset, ChartOptions } from "chart.js";

function DoughnutChart(){
  const doughnutLabelsLine = {
    id: "doughnutLabelsLine",
    afterDraw(chart: Chart<"doughnut">, args: any, options: ChartOptions) {
      const {
        ctx,
        chartArea: { top, bottom, left, right, width, height },
      } = chart;

      chart.data.datasets.forEach((dataset, i) => {
        // console.log(chart.getDatasetMeta(i));
        chart.getDatasetMeta(i).data.forEach((datapoint, index) => {
          console.log(dataset);
          const { x, y } = datapoint.tooltipPosition();
          //Object is possibly undefined
          ctx.fillStyle = dataset?.borderColor[index];
          ctx.fillRect(x, y, 2, 2);
        });
      });
    },
  };

//config...
//dataDoughnut

return (
        <div className="col-span-6">
          <Doughnut
            data={dataDoughnut}
            options={config}
            width={200}
            height={300}
            plugins={[doughnutLabelsLine]}
          />
        </div>
);
}
export default DoughnutChart;

我也试过把它放在if语句中,并使用感叹号,但没有用。我是不是漏掉了什么?
编辑:根据user2057925的建议进行了调整
环圈图标签缐

const doughnutLabelsLine = {
    id: "doughnutLabelsLine",
    afterDraw(chart: Chart<"doughnut">, args: any, options: ChartOptions) {
      const {
        ctx,
        chartArea: { top, bottom, left, right, width, height },
      } = chart;

      chart.data.datasets.forEach((dataset, i) => {
        // console.log(chart.getDatasetMeta(i));
        chart.getDatasetMeta(i).data.forEach((datapoint, index) => {
          console.log(dataset);
          const { x, y } = datapoint.tooltipPosition();
          ctx.save();
          const borderColor = datapoint.options.borderColor as
            | string
            | CanvasGradient
            | CanvasPattern;
          ctx.fillStyle = borderColor;
          // ctx.fillStyle = dataset?.borderColor[index];
          ctx.fillRect(x, y, 10, 10);
          ctx.restore();
        });
      });
    },
  };
ykejflvf

ykejflvf1#

我认为undefined错误与dataset示例无关,而是由于borderColor示例。
无论如何,最好的办法是使用datapoint.options.borderColor,因为:
1.您不需要数据集示例或索引
1.作为ArcElement的数据点在options节点中提供其所有选项,即使它们被配置(使用默认值)。
第一个

相关问题