I’m trying to build a project in JavaScript that utilizes HTML5’s canvas tag. However, I’m running into a few issues due to referencing scopes in my objects/prototypes.
Is it a good idea (or rather, good practice) to just make the canvas element (however many of them there happen to be) global? I’ve been trying to avoid making global variables whenever possible, due to wanting to stick to an OOP-mentality, but I’m not finding many better solutions to this issue.
Any feedback is appreciated.
Your main problem seems to be passing information into events (functions that don’t receive parameters).
The solution to this is closures. Functions can use any variables defined in their scope and you can use this to your advantage.
You can make this more complicated by say, passing a “canvas manager” object instead to allow changing canvases at runtime as well as add other variables you might need…