A limitation of event listener functions is that they are invoked by the browser and are only passed a single parameter, the object representing the event. So we need somewhere else to hold other data that will be needed on successive calls to the listener, such as the graphics context. A simple way to do this is to declare an object outside all of our functions. This is known as a global object. It is not good practice to have many global objects so let's just declare one at the start of our .js file:
const DATA = {};
That creates a new literal object with nothing in it. We can add things to it later. The browser allocates somewhere in memory for it and gives us a reference that we can assign to something we call DATA
. The reference will remain constant even though the contents of the object will change. So capital letters indicate that it is constant and then using the keyword const
instead of let
means that the browser can indicate an error if we try to change it. That helps to keep our program right.
The first thing we need to hold globally so that it can be used in many functions is the graphics context. So in run()
after setting g2
put
DATA.g2 = g2;