1

I want to load an image for one of the data points in a Scatter chart. The problem I have is the image doesn’t load on the initial page/chart render. Image only appears when you click/interact with the chart. I am using react-chartjs-2, any suggestions would be appreciated.

I’ve tried the following (snippet)

import { Scatter, Chart } from "react-chartjs-2";

const chartReference = useRef();
const myImage = new Image(25, 35); 
myImage.src = '/img/myimage.svg';
  
const chartData = {
    datasets: [{
        label: 'my Image',
        data: [{ x: dummyData, y: 25 }],
        pointStyle: myImage,
        radius: 1,
        pointRadius: 10,
        borderWidth: 0,
        type: 'line',
    }],
}

 return (
    <Scatter
        height={height}
        width={width}
        data={chartData}
        options={options}
        plugins={[Zoom]}
        ref={chartReference}
        redraw={true} 
    />
       

I also through of this but where should do I place this?

chartReference.current.chartInstance.data.datasets[0].pointStyle = myImage; 
chartReference.current.chartInstance.update();

If you manage to solve that I would like to ask a part 2 question that is the when you pan the chart unlike the built in data pointStyle the image goes off the y-axis. It only hide when at the charts actual width

Jereme
  • 427
  • 7
  • 15

1 Answers1

1

It should work if you define the Image inside the component constructor...

constructor() {
  super();
  const myImage = new Image(25, 35);
  myImage.src = "/img/myimage.svg";

and create the Scatter chart inside the render method.

render() {
  return (
    <div>
      <Scatter
        data={this.state.chartData }
        options={this.state.chartOptions}
        ...
      />
    </div>
  );
}

Please have a look at this StackBlitz.

uminder
  • 23,831
  • 5
  • 37
  • 72
  • thanks. But I don't want to use class. I'm working with function component with React Hooks. – Jereme Aug 13 '20 at 08:57