Make a javascript canvas rectangle clickable

后端 未结 4 1205
夕颜
夕颜 2021-01-16 22:06

I am creating a simple calculator. Here it is. I am almost done with the basic design but I am confused on how to make the buttons clickable? One trick could be to make a di

4条回答
  •  死守一世寂寞
    2021-01-16 22:31

    You can “press” a drawn key on the canvas by listening for mouseclicks and then hittesting whether the click position is inside any one of the calculator key’s boundary.

    Here is code that will return true if a mouseclick is inside a rectangle:

    function isPointInsideRect(pointX,pointY,rectX,rectY,rectWidth,rectHeight){
        return  (rectX <= pointX) && (rectX + rectWidth >= pointX) &&
                     (rectY <= pointY) && (rectY + rectHeight >= pointY);
    }
    

    If your calculator buttons are round, here is code that will hittest a mouseclick inside a circle:

    function isPointInsideCircle(pointX,pointY,circleX,circleY,radius){
        var dx=circleX-pointX;
        var dy=circleY-pointY;
        return  ( dx*dx+dy*dy<=radius*radius  );
    }
    

提交回复
热议问题