Get a reference to a Canvas element from its context?
In one part of my code, I call getContext('2d')
on a canvas
element to produce a CanvasRenderingContext2D object. That object 开发者_如何学Pythongoes 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.
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;
精彩评论