I'm writing an extension to the javascript context object.
What I want to achieve:
In the end, I want to have a function which takes only one argument, canvas. From there on it should extend that canvas element with all kinds of extra functionality that I will write myself.
So basically, turning a canvas into a special canvas as follows:
Html
<canvas id='normal'></canvas>
<canvas id='special'></canvas>
Javascript
var normal = document.getElementById("normal"),
special = document.getElementById("special");
var Extendedctx = function (canvas) {
// Magic?
}
Extendedctx(special); // Extends the "special" canvas's context (ctx) with lots of extra functionality.
special.getContext('2d').nonBuiltinFunction(); // Should work
normal.getContext('2d').nonBuiltinFunction(); // Should throw an exception
The normal canvas however, should stay exactly the same. So, extending the prototype of the builtin ctx-object is not a viable solution.
I'm trying to achieve this by doing the following:
var canvas = document.getElementById('testcanvas'),
ctx = canvas.getContext('2d'),
Extendedctx = function (canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.__proto__ = Object.create(this.ctx);
return this
}, pad = new Extendedctx(canvas);
pad.fillRect(0, 0, 40, 40);
However, the following exception occurs at the last line:
Uncaught TypeError: Illegal invocation
According to the following SO post quote, this should make sense:
In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
So, to fix that you'll have to call pad.fillRect.call(pad.ctx, 0, 0, 40, 40);
Now, this would get annoying and messy really quickly. What I want to end up with is that:
pad.fillRect(0, 0, 40, 40);
would simply work, as well as any other inherited function I might want to use (eg ctx.arc
)
I really don't know what to do here, I tried googling something along the lines of 'altering functions calls in javascript' and such. No real useful results.
Here's the jsfiddle in case you need to fiddle around with the js