Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add prototype functions to canvas context

I want to add some methods to the context retrieved from a canvas object. For example I'd like to have this prototype method added to any 2D drawing context which resets the transform to an identity matrix:

Context.prototype.identity = function() {
  this.setTransform(1, 0, 0, 1, 0, 0);
}

and then whenever I request a 2D context like so

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

The context object automatically has an identity() method available for me to reset any transform back to the default state. I know I can attach my prototype method by saying:

context.identity = function() { context.setTransform(1, 0, 0, 1, 0, 0); }

But I have to do this explicitly every time, and I'd prefer the "Context.prototype.identity = function" syntax as it would attach the method for me automatically.

Curious

like image 346
sysrpl Avatar asked Aug 07 '11 17:08

sysrpl


People also ask

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 you get the rendering context of a canvas?

Reference the Canvas in JavaScript We'll use the getElementById() document method to target the <canvas> tag through the document object model and assign that to the variable canvas. var canvas = document. getElementById("test-canvas"); Next, we have to create the rendering context of the canvas element.

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.

What is CTX in canvas?

It is just name for variable. It could be anything. Ctx is just short word for ConTeXt.


1 Answers

this should work:

CanvasRenderingContext2D.prototype.identity = function() { 
    return this.setTransform(1, 0, 0, 1, 0, 0); 
}
like image 122
gion_13 Avatar answered Sep 18 '22 00:09

gion_13