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?
You cannot use multiple contexts for one canvas element. In WebKit, this is explicitly mentioned in the source: // A Canvas can either be "2D" or "webgl" but never both.
The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and other objects.
getContext() The HTMLCanvasElement. getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported, or the canvas has already been set to a different context mode.
It is just name for variable. It could be anything. Ctx is just short word for ConTeXt.
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 accessibleIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With