Make a javascript canvas rectangle clickable

后端 未结 4 1217
夕颜
夕颜 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: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).

提交回复
热议问题