开发者

How do you add prototype functions to canvas context

开发者 https://www.devze.com 2023-03-26 17:58 出处:网络
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

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() { co开发者_Go百科ntext.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


this should work:

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

精彩评论

暂无评论...
验证码 换一张
取 消