0

我无法在 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

这里是选项配置(简化),我也尝试在“插件”中包装“注释”,但它不起作用:

  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: {
    ...
  },

我究竟做错了什么?

4

1 回答 1

1

看起来您正在尝试实现注释插件,就好像您将它集成到当前的 chart.js 版本一样。例如,您在plugins.

这是一个适用于给定版本的示例。请注意,我立即在给出所需注释的内容中添加了annotation对象。options(在我的例子中,以红线的形式出现。)

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/

于 2021-11-27T11:27:48.747 回答