scr*_*rd3 15 javascript canvas
我正在用javascript创建一个库,我想知道是否有某种方法可以向画布添加新类型的上下文而不是2d
var ctx.document.getElementById('canvas').getContext("othercontext");
Run Code Online (Sandbox Code Playgroud)
我将创建一个具有所有正常2d属性的othercontext,以及更多.有没有办法做到这一点?
aps*_*ers 10
您无法完全执行此操作,但您可以挂钩该getContext方法并返回具有额外属性和方法的扩展2D上下文:
(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;
}
})();
Run Code Online (Sandbox Code Playgroud)
因此,调用someCanvas.getContext("othercontext").drawSmileyFace()将调用drawSmileyFace已添加到普通2D上下文返回值的getContext("2d").
但是,我在建议在实际部署的代码中使用此模式时犹豫不决,因为:
getContext将阻止该上下文类型可访问| 归档时间: |
|
| 查看次数: |
1231 次 |
| 最近记录: |