Reputation: 7416
I'm making a library in javascript and I wanted to know if there was some way to add a new type of context to the canvas rather than 2d
var ctx.document.getElementById('canvas').getContext("othercontext");
where I would create a othercontext with all the normal 2d properties, plus some more. Is there any way to do this?
Upvotes: 15
Views: 1962
Reputation: 115950
You can't do this exactly, but you can hook the getContext
method and return an extended 2D context that has extra properties and methods:
(function() {
// save the old getContext function
var oldGetContext = HTMLCanvasElement.prototype.getContext;
// overwrite getContext with our new function
HTMLCanvasElement.prototype.getContext = function(name) {
// if the canvas type requested is "othercontext",
// augment the 2d canvas before returning it
if(name === "othercontext") {
var plainContext = oldGetContext.call(this, "2d");
return augment2dContext(plainContext);
} else {
// get the original result of getContext
return oldGetContext.apply(this, arguments);
}
}
// add methods to the context object
function augment2dContext(inputContext) {
inputContext.drawSmileyFace = function() { /* ... */ };
inputContext.drawRandomLine = function() { /* ... */ };
inputContext.eraseStuff = function() { /* ... */ };
return inputContext;
}
})();
Thus, a call to someCanvas.getContext("othercontext").drawSmileyFace()
will invoke the drawSmileyFace
that has been added to the ordinary 2D-context return value of getContext("2d")
.
However, I'm hesitant to suggest using this pattern in actual deployed code because:
getContext
will prevent that context type from being accessibleUpvotes: 10
Reputation: 63812
The simple answer is no, that's not possible.
Canvas context's are intended to be something browser vendors (Chrome, Firefox, etc) create, not JavaScript/Canvas authors (you and me).
Aside from "2d"
and "webgl"
, The canvas specification states that browser vendors may define their own (experimental) contexts (like "moz-3d"), but again, not JavaScript authors.
Stick with adding new methods to the existing context. (Or making a wrapper, etc)
Upvotes: 0
Reputation: 9
I'm pretty sure this is impossible. I suggest wrapping it in an object or add methods to the context
Upvotes: 0
Reputation: 53311
While I haven't been able to dig up anything that definitively answers your question, I would tentatively state that it's highly unlikely that you're able to define a new context yet in any implementations of Javascript (and even if you could, browsers probably wouldn't support it for a while). You could, however, modify already existing "2d" contexts with additional properties, perhaps by running them through a constructor?
Upvotes: 0