Hover to change color of canvas

10,905

Your :hover will never be triggered.

Circles drawn on html canvas are not DOM elements. Instead they are like forgotten painted pixels on a canvas.

These are the steps to apply a hover-effect to your circle

  • Keep track of your circle's definition (x,y,radius,etc) in a javascript object.

  • Listen for mousemove events and test if the mouse is inside your circle

  • When the mouse enters or leaves your circle, redraw your circle

This is how those steps might look in code:

Demo: http://jsfiddle.net/m1erickson/rV9cZ/

Keep track of your circle's definition (x,y,radius,etc) in a javascript object.

var myCircle={
    x:150,
    y:150,
    radius:25,
    rr:25*25,  // radius squared
    hovercolor:"red",
    blurcolor:"green",
    isHovering:false
}

Listen for mousemove events and test if the mouse is inside your circle

function handleMouseMove(e){
  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);
  var dx=mouseX-myCircle.x;
  var dy=mouseY-myCircle.y;

  // math to test if mouse is inside circle
  if(dx*dx+dy*dy<myCircle.rr){

      // change to hovercolor if previously outside
      if(!myCircle.isHovering){
          myCircle.isHovering=true;
          drawCircle(myCircle);
      }

  }else{

      // change to blurcolor if previously inside
      if(myCircle.isHovering){
          myCircle.isHovering=false;
          drawCircle(myCircle);
      }
  }

}

When the mouse enters or leaves your circle, redraw your circle

function drawCircle(circle){
    ctx.beginPath();
    ctx.arc(circle.x,circle.y,circle.radius,0,Math.PI*2);
    ctx.closePath();
    ctx.fillStyle=circle.isHovering?circle.hovercolor:circle.blurcolor;
    ctx.fill();
}
Share:
10,905
user3114036
Author by

user3114036

Updated on June 04, 2022

Comments

  • user3114036
    user3114036 over 1 year

    I am new in canvas can anyone please help to short this issue.

    I create 5 canvas circle. When I hover on any circle I need to change canvas color only, when hover on circle I added one class on canvas but is it possible to change only color. I don't want to create canvas again change only color when hover.

    $(document).ready(function(){
     $('.menuballs').hover(function () {
      $(".menuballs").children('canvas').toggleClass('hover-intro');
       if($(this).is(':hover'))
       {
         var c = document.getElementsByClassName("hover-intro");            
         var graphics = c.getContext( '2d' );
         graphics.fillStyle = 'green';
         graphics.fill();
       }
      });
    });
    

    Try this as taking hover-intro class but its given HTMLElement, and I need CanvasElement to fill in circle.