Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get canvas from context

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'? 
like image 832
pimvdb Avatar asked Mar 15 '11 16:03

pimvdb


People also ask

What is canvas get context?

getContext() The HTMLCanvasElement. getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported, or the canvas has already been set to a different context mode.

What is canvas getContext (' 2D ')?

The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and other objects.

How do I get data from canvas?

The getImageData() method returns an ImageData object that copies the pixel data for the specified rectangle on a canvas. Note: The ImageData object is not a picture, it specifies a part (rectangle) on the canvas, and holds information of every pixel inside that rectangle.

Can a canvas have multiple contexts?

You cannot use multiple contexts for one canvas element. In WebKit, this is explicitly mentioned in the source: // A Canvas can either be "2D" or "webgl" but never both.


1 Answers

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.

like image 163
Jack Lawson Avatar answered Sep 23 '22 23:09

Jack Lawson