【发布时间】:2016-06-14 12:39:05
【问题描述】:
我正在尝试利用 Web 组件、模板和影子 DOM 来创建画布元素。问题是我无法在原型中获取上下文,或者在创建阴影时出现此错误: HierarchyRequestError: Failed to execute 'createShadowRoot' on 'Element': Author-created shadow root is disabled for this element.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="import" href="mycanvas.html">
</head>
<body>
<canvas is="my-canvas"></canvas>
</body>
</html>
<template id="mytemplate">
<style>
p {color:green;}
span {text-decoration: underline;}
canvas {background-color: #f00;
width:300px;}
</style>
</template>
<script>
(function() {
var myPrototype= Object.create(HTMLElement.prototype);
var myDocument=document.currentScript.ownerDocument;
myPrototype.createdCallback=function() {
var shadow= this.createShadowRoot();
var template=myDocument.querySelector("#mytemplate");
var clone= document.importNode(template.content, true);
shadow.appendChild(clone);
} //end prototype
var myCanvas= document.registerElement('my-canvas', {
prototype: myPrototype,
extends:'canvas'
});
}());
</script>
【问题讨论】:
-
thisvar shadow= this.createShadowRoot();是什么?</html>在<template>元素之前html? -
在
canvas元素上创建shadowRoot的目的是什么? -
即使我不创建阴影,我仍然无法获得上下文。我是 Web 组件的新手,所以我有点困惑 @guest271314
-
“仍然无法获取上下文”是什么意思?你想达到什么目的?
-
我有一个画布的绘图功能,但我想使用 Web 组件来实现它,所以当我尝试 var ctx=canvas.getContext('2d') 时,无论我如何尝试获取html canvas 元素(带有 getElementsByTagName 或其他任何东西)它说 getContext 不是函数@ guest271314
标签: javascript templates dom canvas shadow