Chartjs-Line chart Change background color of shaded region on hover (Chartjs)

0👍

Here is the stackblitz link, made the change in your code and it is live

Chart.js does not yet provide any property or method to a change of color of the area under a line graph on hover (to be specific).

But you can achieve this by some other method by re-rendering your canvas on hover, this can be smooth if you have your own custom made hooks, (This is a hackish way of achieving what you want, IT WORKS !!! but I personally will not recommend this)

Here is the explanation

  1. I have added one state which will toggle to true & false on Hover

    const [ isHover, hoverToggle ] = useState(false)

  2. I have shifted const data inside of App function

  3. To choose background-color to add this condition

    backgroundColor: isHover ? "red" : "blue"
    
  4. Then in onHover event I have added two conditions

a)

if ( event.type === "mousemove" && !isHover ) {
    hoverToggle(true);
}

b)

if ( event.type === "mouseout" ||
     event.type === "mouseleave" ||
     event.type === "mouseup"
   ) {
        hoverToggle(false);
     }
  1. And most important part pass isHover in useEffect‘s array so it will be revoked on isHover toggle

I personally recommend d3.js for such type of requirements it is a little complex but you can get whatever you want in the graph.

Leave a comment