HTMLCanvasElement extension in user element

I cannot get the 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 this a mistake, an omission or something else?

PS I'm looking for a solution for chrome-based browsers.

+4
source share
1 answer

Here you are missing some points, when expanding your own object, you should use the option extends:

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

And you cannot create directly custom type extensions, therefore you cannot do it createElement("custom-canvas"), you must use the attribute is, and for this you must use createElementwith two parameters:

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

By doing all this, you can use an extension like:

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

All Articles