Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hover to change color of canvas

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.

like image 559
user3114036 Avatar asked Dec 20 '25 19:12

user3114036


1 Answers

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();
}
like image 55
markE Avatar answered Dec 22 '25 10:12

markE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!