sysrpl
sysrpl

Reputation: 1589

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

Upvotes: 14

Views: 6339

Answers (1)

gion_13
gion_13

Reputation: 41533

this should work:

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

Upvotes: 31

Related Questions