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
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.
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.
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.
It is just name for variable. It could be anything. Ctx is just short word for ConTeXt.
this should work:
CanvasRenderingContext2D.prototype.identity = function() {
return this.setTransform(1, 0, 0, 1, 0, 0);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With