Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a reference to a Canvas element from its context?

Tags:

html

dom

canvas

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.

like image 606
Steven Bedrick Avatar asked Dec 28 '22 08:12

Steven Bedrick


1 Answers

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;
like image 90
Simon Sarris Avatar answered Dec 31 '22 12:12

Simon Sarris