【问题标题】:Canvas Shadow DOM and Web Components画布阴影 DOM 和 Web 组件
【发布时间】: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>

【问题讨论】:

  • this var shadow= this.createShadowRoot(); 是什么? &lt;/html&gt;&lt;template&gt; 元素之前 html?
  • canvas 元素上创建shadowRoot 的目的是什么?
  • 即使我不创建阴影,我仍然无法获得上下文。我是 Web 组件的新手,所以我有点困惑 @guest271314
  • “仍然无法获取上下文”是什么意思?你想达到什么目的?
  • 我有一个画布的绘图功能,但我想使用 Web 组件来实现它,所以当我尝试 var ctx=canvas.getContext('2d') 时,无论我如何尝试获取html canvas 元素(带有 getElementsByTagName 或其他任何东西)它说 getContext 不是函数@ guest271314

标签: javascript templates dom canvas shadow


【解决方案1】:

无论我如何尝试获取 html 画布元素(使用 getElementsByTagName 或其他)它说 getContext 不是 功能

在定义myPrototype 时尝试用HTMLCanvasElement.prototype 替换HTMLElement.prototype

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2014-01-21
    • 1970-01-01
    • 2016-04-15
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多