Mouse hover canvas/shape

前端 未结 1 2036
南旧
南旧 2020-12-22 09:43

I have this code on in Jquery. I would like to change the opacity percentage of the individual shapes on mouseover. I normaly don\'t have this kind of problems, but I don\'t

相关标签:
1条回答
  • 2020-12-22 10:23

    Use context.isPointInPath to hit test if the mouse is inside one of your paths.

    Here's a quick example:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    function reOffset(){
        var BB=canvas.getBoundingClientRect();
        offsetX=BB.left;
        offsetY=BB.top;        
    }
    var offsetX,offsetY;
    reOffset();
    window.onscroll=function(e){ reOffset(); }
    window.onresize=function(e){ reOffset(); }
    
    ctx.fillStyle='blue';
    
    var shapes=[];
    shapes.push(
        [{x:67,y:254},{x:57,y:180},
            {x:87,y:92},{x:158,y:116},
            {x:193,y:168},{x:196,y:244},
            {x:135,y:302},{x:67,y:204}]
    );
    
    ctx.globalAlpha=0.25;
    for(var i=0;i<shapes.length;i++){
        defineshape(shapes[i]);
        ctx.fill();
    }
    ctx.globalAlpha=1.00;
    
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    
    function defineshape(s){
        ctx.beginPath();
        ctx.moveTo(s[0].x,s[0].y);
        for(var i=1;i<s.length;i++){
            ctx.lineTo(s[i].x,s[i].y);
        }
        ctx.closePath();
    }
    
    function handleMouseMove(e){
      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();
      // mouse position
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // test if mouse is inside any shape(s)
      // and redraw different alpha based on hovering
      ctx.clearRect(0,0,cw,ch);
      for(var i=0;i<shapes.length;i++){
          defineshape(shapes[i]);
          if(ctx.isPointInPath(mouseX,mouseY)){
              ctx.globalAlpha=1.00;
          }else{
              ctx.globalAlpha=0.25;
          }
          ctx.fill();
      }
    }
    body{ background-color: ivory; }
    #canvas{border:1px solid red; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <h4>Hover over shape with mouse.</h4>
    <canvas id="canvas" width=300 height=350></canvas>

    0 讨论(0)
提交回复
热议问题