score:2

Accepted answer

it looks like you are trying to implement the annotations plugin as if you would integrate it to a current chart.js version. e.g. your define your annotations in plugins.

this is an example that works with the given versions. please note that i added the annotation object right away in options what gives the wanted annotation. (in my example in form of a red line.)

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;

you can see it working here: https://codesandbox.io/s/chart-js-2-9-4-annotation-example-f3h7d?file=/src/linegraph.js

chart.js plugin annotation documentation for 0.5.7: https://www.chartjs.org/chartjs-plugin-annotation/0.5.7/


Related Query

More Query from same tag