是否可以在元素内绘制 canvas ?

Is it possible to draw on a canvas inside an Element?

我想在我的聚合物元素内的 canvas 上绘制一个形状。问题是我在初始化我的自定义元素之前 运行 canvas 绘图代码。我尝试了 ready 功能,但它仍然无法正常工作。

这是我的元素代码:

<link rel="import" href="../../bower_components/polymer/polymer-element.html">

<dom-module id="draw-section">
     <template>
    <style>
    .left{position:absolute;
       overflow:hidden;
      width: calc(100vw - 300px);
      height: calc(100vh - 48px);

    }
    .right{
      width: 300px;
      height: 100%;
      overflow: hidden;
      float: right;
    }
    .right-container{
      padding: 14px;
    }
    #myCanvas{
      background: #fafafa;
    }
    </style>
  <canvas class="left" id="myCanvas" width="300" height="300"></canvas>
  <div class="right">
    <div class="right-container">
      Right Container
    </div>
  </div>
  </template>
     <script>
          class DrawSection extends Polymer.Element {
               static get is() {
                    return 'draw-section';
               }
               ready() {
                    super.ready();
                    var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
               }

          }
          window.customElements.define(DrawSection.is, DrawSection);
     </script>
</dom-module>

如果我 运行 此代码出现错误提示:

Uncaught TypeError: Cannot read property 'getContext' of null
    at HTMLElement.ready (draw-section.html:40)
    at HTMLElement._enableProperties (property-accessors.html:531)
    at HTMLElement.connectedCallback (element-mixin.html:630)
    at HTMLElement._attachDom (element-mixin.html:690)
    at HTMLElement._readyClients (element-mixin.html:663)
    at HTMLElement._flushClients (property-effects.html:1518)
    at HTMLElement._propertiesChanged (property-effects.html:1644)
    at HTMLElement._flushProperties (property-accessors.html:549)
    at HTMLElement.ready (property-effects.html:1606)
    at HTMLElement.ready (element-mixin.html:649)

是否可以在 Polymer Element 中的 canvas 上绘图?我是 Polymer 的新手,没有太多经验。

document.getElementById 用于访问 dom 之外的元素。 你需要使用 this.$ 来获取元素

要获得 canvas 您可以使用:

this.$["myCanvas"]

而不是:

document.getElementById("myCanvas")