Hover to change color of canvas

前端 未结 1 1687
野性不改
野性不改 2020-12-20 03:16

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

相关标签:
1条回答
  • 2020-12-20 03:57

    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();
    }
    
    0 讨论(0)
提交回复
热议问题