I'd like to create an object which I can pass around in place of a built-in object (specifically, an instance of CanvasRenderingContext2D
). I'd like most of the methods to forward to the built-in equivalents, but I'd also like to add some methods of my own & wrap some of the built-ins.
Here's what I've come up with:
function MyContext(ctx) {
for (var k in ctx) {
(function(k) {
if (typeof(ctx[k]) == 'function') {
this[k] = ctx[k].bind(ctx);
} else {
Object.defineProperty(this, k, {
get: function() { return ctx[k]; },
set: function(x) { ctx[k] = x; }
});
}
}).bind(this)(k);
}
this.stroke = function() {
console.log('called stroke');
ctx.stroke();
};
}
A MyContext
object can be used exactly as the built-in CanvasRenderingContext2D
is:
var canvas = document.querySelector('canvas'),
ctx = canvas.getContext('2d');
var mtx = new MyContext(ctx);
mtx.beginPath();
mtx.moveTo(100, 50);
mtx.lineTo(200, 50);
mtx.lineTo(200, 75);
mtx.closePath();
mtx.strokeStyle = 'red';
mtx.stroke();
with the exception that the stroke
call logs.
Is this the best way to achieve this? Is it possible to do this more efficiently using prototype trickery?