0
\$\begingroup\$

If I will draw a button with canvas with any programming language (java,javascript....) I want to know how to add the events to what I've drawn for example If I will draw a button piture then what I have to do to be able to make an onclick event to that button in my case I'm trying to make a javascript application but In canvas it's a drawing so how could we add a button ? Please comment with any idea you have ?

Example : When I run my game the player will find a welcome page with a start button drawn with Photoshop or something like that and it has been drawn by a canvas so how could I add a MouseListener to that button ?

\$\endgroup\$
1
\$\begingroup\$

The straightforward method is to keep a list of trigger areas and on each onclick event on the canvas compare the cursor location to the areas and trigger the correct event handler.

How you express those areas is up to you, in extremis you can assign a handler to each pixel using a second bitmap where the exact color of the second bitmap is an index to the handler.

\$\endgroup\$
  • \$\begingroup\$ I second the first idea (you'll have to keep the coordinates of "buttons", and check at each click if one of the buttons is clicked ; and map the buttons to an action.) However I don't think the "pixel" bitmap sounds like a good idea (this would use lots of memory, but most of your UI will probably not be clickable, will it ?). \$\endgroup\$ – phtrivier Mar 18 '16 at 13:57
  • \$\begingroup\$ OK but does all the games in the world work with this method I mean is there any framework could do such a thing in Javascript , I mean a framework help me add an element and it does the work of adding it in the canvas and to onclick Listener and do the analysis part and give me the specified button automatically ? Please answer me :) :) \$\endgroup\$ – Khalil Bz Mar 18 '16 at 13:58
  • \$\begingroup\$ @phtrivier it depends, It does allow the artist to define the clickable areas. \$\endgroup\$ – ratchet freak Mar 18 '16 at 14:00
  • \$\begingroup\$ @KhalilBz most games would use a collection or rectangles and test them one by one (unless there is a space partitioning used). The Rect would hold a {left, right, top, bottom} coordinates and a reference to the button it represents. \$\endgroup\$ – ratchet freak Mar 18 '16 at 14:01
  • \$\begingroup\$ @ratchetfreak I see. I also makes it possible to use "non rectangular" buttons easily (to the expense of memory), which can be nice. \$\endgroup\$ – phtrivier Mar 18 '16 at 14:04
0
\$\begingroup\$

You could try having 2 layers stacked on top of each other with a default button underneath your canvas drawn one

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.