Search code examples
reactjscanvaschart.jsreact-chartjs-2

background image is not displaying in react-chartjs-2


I want use image background in react-chartjs-2 but its not working. I tried in plane chartjs page and its working without any problem.

const image = new Image();
image.src = 'https://www.chartjs.org/img/chartjs-logo.svg';


const plugin = {
  id: 'custom_canvas_background_image',
  beforeDraw: (chart) => {
    if (image.complete) {
      const ctx = chart.ctx;
      const {top, left, width, height} = chart.chartArea;
      const x = left + width / 2 - image.width / 2;
      const y = top + height / 2 - image.height / 2;
      ctx.drawImage(image, x, y);
    } else {
      image.onload = () => chart.draw();
    }
  }
};

 export default function Chart() {
   return <Line options = {
      options
   }
   data = {
      data
   }
   plugins = {
    plugin
   }
   />;
}


Solution

  • plugins must be defined as an array as follows:

    plugins = {[
      plugin
    ]}
    

    I couldn't find this information on the react-chartjs-2 page directly but taking a look at types.ts on GitHub, I found this...

    /**
     * The plugins array that is passed into the Chart.js chart
     * @see https://www.chartjs.org/docs/latest/developers/plugins.html
     * @default []
     */
    plugins?: Plugin<TType>[];