Search code examples
javascriptcanvaschromiumcustom-element

Extending HTMLCanvasElement in Custom Element issue


I can not get a drawing context of a custom canvas element.

var customCanvas      = Object.create(HTMLCanvasElement.prototype),
    canvasConstructor = document.registerElement("custom-canvas", { prototype: customCanvas }),
    canvas            = document.createElement("custom-canvas"),
    ctx               = canvas.getContext("2d"); // Uncaught TypeError: Illegal invocation

Is it a bug, omission or something else?

P.S. I search for a solution for chromium-based only browsers.


Solution

  • You're missing some points here, when extending a native object you must use the extends option:

    canvasConstructor = document.registerElement("custom-canvas", { prototype: customCanvas, extends: 'canvas' });
    

    And you can't create custom type extensions directly, so you can't do createElement("custom-canvas") you must use the is attribute and to do that you must use the createElement with two parameters:

    canvas = document.createElement('canvas', 'custom-canvas');
    //canvas in HTML will be <canvas is="custom-canvas"></canvas>
    //<custom-canvas></custom-canvas> is invalid
    

    Doing all this way you will be able to use your type extension:

    ctx = canvas.getContext('2d'); //no error :)