向画布对象添加新上下文

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将阻止该上下文类型可访问
  • 更一般地说,扩展主机对象(如DOM元素)的功能通常是不好的做法,因为主机对象可以(但通常不会)在完全普通的操作(例如属性访问)上抛出错误