在Charts 2.9.x中使用chartjs-plugin-annotation 0.5.7和React

eulz3vhy  于 2023-06-22  发布在  Chart.js
关注(0)|答案(1)|浏览(199)

我无法在Chartjs中配置插件chartjs-plugin-annotation。
在文档中,我安装了V 0.5.7,因为我使用的是Chart.js V 2.9.4。
这里我的配置:
注册插件:

import Chart from "chart.js";
import annotationPlugin from "chartjs-plugin-annotation";

Chart.plugins.register(annotationPlugin);
//Chart.pluginService.register(annotationPlugin); //also tried this but doesn't work

这里的选项配置(简化),我也试图 Package “注解”在“插件”,但它不工作:

scales: {
    yAxes: [
      {
        scaleLabel: {
          ...
        },
        ticks: {
          ...
        },
        gridLines: {
          ...
        },
      },
    ],
    xAxes: [
      {
        gridLines: {
          ...
        },
        ticks: {
          ...
        },
      },
    ],
  },
  maintainAspectRatio: false,
  legend: {
    ...
    labels: {
      ...
    },
  },
  tooltips: {
    ...
  },
  annotation: {
    annotations: [
      {
        type: "line",
        mode: "horizontal",
        scaleID: "yAxes",
        value: 2.62,
        borderColor: "white",
        borderWidth: 4,
      },
    ],
  },
  hover: {
    ...
  },

我做错了什么?

ccrfmcuu

ccrfmcuu1#

看起来你正在尝试实现注解插件,就好像你要将它集成到当前的chart.js版本中一样。例如,在plugins中定义注解。
这是一个适用于给定版本的示例。请注意,我在options中添加了annotation对象,它给出了所需的注解。(在我的例子中,以红线的形式。

import React, { useEffect, useRef } from "react";
import Chart from "chart.js";
import annotationPlugin from "chartjs-plugin-annotation";

Chart.pluginService.register(annotationPlugin);

const LineGraph = () => {
  const chartRef = useRef(null);

  useEffect(() => {
    if (chartRef?.current) {
      const chartToDraw = chartRef.current.getContext("2d");

      new Chart(chartToDraw, {
        type: "line",
        data: {
          labels: ["Jan", "Feb", "March"],
          datasets: [
            {
              label: "Sales",
              data: [86, 67, 91]
            }
          ]
        },
        options: {
          annotation: {
            drawTime: "afterDatasetsDraw", // (default)
            events: ["click"],
            dblClickSpeed: 350, // ms (default)
            annotations: [
              {
                drawTime: "afterDraw",
                id: "a-line-1",
                type: "line",
                mode: "horizontal",
                scaleID: "y-axis-0",
                value: "25",
                borderColor: "red",
                borderWidth: 2
              }
            ]
          }
        }
      });
    }
  }, []);

  return (
    <div className={{ width: "100%", height: 500 }}>
      <canvas id="myChart" ref={chartRef} />
    </div>
  );
};

export default LineGraph;

你可以看到它在这里工作:https://codesandbox.io/s/chart-js-2-9-4-annotation-example-f3h7d?file=/src/LineGraph.js
0.5.7的Chart.js插件注解文档:https://www.chartjs.org/chartjs-plugin-annotation/0.5.7/

相关问题