0

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.

clicheName
  • 889
  • 2
  • 11
  • 16
  • ?? No, I don't think it's good practice; in fact it doesn't really even make sense. Whether a reference to a canvas object is in a global variable or not has no effect on how the canvas works. – Pointy Feb 08 '11 at 20:14
  • What I mean is (as an example): let's say I want to alter text on the canvas everytime the mouse is moved (for x and y coordinate values). The function that would have to be in might not be able to reference the canvas element's other methods of redrawing what *else* should be on the canvas, too. It's a bit hard to explain without providing an actual script, which I don't have much time to do at the moment, unfortunately. – clicheName Feb 08 '11 at 20:20
  • 1
    clicheName, you can pass along the cavas object to the methods that require it – Tom Feb 08 '11 at 20:23

2 Answers2

4

It's actually never a good idea to clobber the global object with variables / references. It's avoidable in almost all situations.

You mentioned you're following an "OOP-mentality" which makes it even more worse. In this case, you obviously did something very wrong in your design concept. Back to the drawingboard!

As I mentioned many times, a minimum effort to avoid this is to create a Function context, which represents the scope if your code.

(function() {
    // all of your code
    var canvas = document.getElementById('mycanvas');
}());
jAndy
  • 231,737
  • 57
  • 305
  • 359
2

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.

function make_event_handler(canvas){
    function my_event_handler(){
        alert('look, I can use '+canvas);
    }
    return my_event_handler;
}

elem.onclick = make_event_handler(canvas);

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...

Community
  • 1
  • 1
hugomg
  • 68,213
  • 24
  • 160
  • 246