4

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.

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Steven Bedrick
  • 663
  • 2
  • 8
  • 16

1 Answers1

10

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
  • 62,212
  • 13
  • 141
  • 171