Reputation: 154818
Is there any way to obtain the canvas that a context is used for?
Why I'm asking is because I'm creating a prototype function for CanvasRenderingContext2D
in which I need the width/height of the canvas element.
E.g.:
var cv = document.getElementById('canvas');
var ctx = cv.getContext('2d');
// Using only 'ctx', how to get 'cv'?
Upvotes: 51
Views: 49406
Reputation: 2505
ctx.canvas
should return the canvas DOM node, from which you can get height and width.
I tried it with https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage
Firefox was able to return ctx.canvas, as well as ctx.canvas.width and ctx.canvas.height. Also confirmed in Chrome.
Upvotes: 72
Reputation: 310842
Try this to check for yourself:
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var isSameObject = canvas === context.canvas;
alert(isSameObject
? 'context.canvas gives expected result'
: 'unexpected result');
Here's the above in a jsFiddle.
Upvotes: 4