在自定义元素问题中扩展HTMLCanvasElement

时间:2015-03-11 11:27:42

标签: javascript canvas chromium custom-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

是错误,遗漏还是其他什么?

P.S。我为仅基于铬的浏览器搜索解决方案。

1 个答案:

答案 0 :(得分:4)

您在此处遗漏了一些要点,在扩展原生对象时,您必须使用extends选项:

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

而且您无法直接创建custom type extensions,因此您无法createElement("custom-canvas")必须使用is属性,为此您必须使用createElement {1}}有两个参数:

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

这样做可以使用你的类型扩展名:

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