Make a javascript canvas rectangle clickable

后端 未结 4 1171
夕颜
夕颜 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  );
    }
    
    0 讨论(0)
  • 2021-01-16 22:36

    A possibility would be to use an actual image of a calculator, then you could use HTML map to define where the buttons are.

    Updated: here is an example of map/area in use, similar to the SVG example given elsewhere on this page.

    0 讨论(0)
  • 2021-01-16 22:38

    Since this looks like it is all pure graphics, one thing I’ve done in the past is just listen for where the mouse presses are and check if I’ve clicked inside a button. It’s pretty manual; basically you’d be making your own button/button primitive handling structure.

    It would look something like:

    // define some button objects (can also set the press handlers, etc)
    // this should actually be in a Button ‘class’ of some sort
    var buttonA = {x: 0, y: 320, width: 50, height: 80};
    var buttonB = {x: 250, y: 320, width: 50, height: 80};
    
    //insert some rendering code to draw the buttons based on the button objects above
    
    // and when the mouse has been pressed
    function mousePressed(inputEvent){
         // loop in here to check which button has been pressed by going through the button objects and responding as needed
    }
    canvas.addEventListener(“click”, mousePressed, false);
    

    I think it’s basically reinventing the wheel here so I’d check to see if there are existing libraries/frameworks first (I did it this way as a learning exercise).

    0 讨论(0)
  • 2021-01-16 22:46

    I would recommend using SVG if you are looking to bind to graphic elements. The canvas element does not allow binding as its graphics are not considered part of the DOM. See here for a demo of binding to SVG elements.

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