views:

16

answers:

1

In one part of my code, I call getContext('2d') on a canvas element to produce a CanvasRenderingContext2D object. That object goes on to get passed around a fair bit from function to function, and at a later point in the code it'd be handy to be able to get a reference to the original canvas dom element that produced a given context. I can't find anything in the spec that provides for this, but it seems like the sort of thing that ought to be possible. Ideas?

I can think of plenty of workarounds (pass the canvas element along with its context, etc.) but my code's complicated enough already and I'd rather do it directly. :-)

+4  A: 

So you've got your context:

var ctx = myCanvas.getContext('2d'); // the canvas' 2d context

later on you can always do:

ctx.canvas // the context's canvas, which in this case is the same as myCanvas

From the Canvas spec:

interface CanvasRenderingContext2D {

  // back-reference to the canvas
  readonly attribute HTMLCanvasElement canvas;
Simon Sarris
OK, now I'm embarrassed. I *swear* I checked the spec for something like that, I must be going blind. Thanks!
Steven Bedrick