Skip to content
Advertisement

call a method from a Rectangle class in the main class

I am trying to retrieve a method from the Rectangle Class in the Main Class, but it is not working. The goal would be that the user clicks on the Rectangle button and then a Rectangle appears. However, the rectangle must not disappear again. Additionally, the user should be able to change the properties (like size and position).

I am not sure if I should try the callback function? I would really appreciate your help!

Thanks a lot in advance!

JavaScript

Advertisement

Answer

It is in fact working (the rect.draw() function fires when you click the button). You can verify this by placing a print statement in the callback function:

JavaScript

Your problem is that the rectangle is only drawn for that single instant when the button is clicked. Your main draw() loop keeps looping without any call to rect.draw() so you never see it again.

There are many ways you could restructure your code to keep the rectangle on screen. One option would be to not instantiate the rectangle until the button is clicked.

Then, in your main draw loop you can check to see if the rectangle exists and if so draw it to the screen. Since this will happen every loop, you will always see it on screen (once it’s created), and you can update the dimensions of the rectangle and see it update on screen.

Here’s an abbreviated example to show what I mean (Rectangle class not shown):

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement