简体   繁体   中英

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?

PS I search for a solution for chromium-based only browsers.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM