2017-10-07 67 views
1

我想在聚合物元素内的画布上绘制一个形状。问题是我在初始化自定义元素之前运行画布绘制代码。我尝试了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) 

是否可以得出一个聚合物元件内的画布上?我是聚合物新手,我没有太多经验。

回答

2

document.getElementById用于访问元素ouside你的dom。 你需要使用这个$获取该元素

拿到帆布是你可以使用:的

this.$["myCanvas"] 

代替:

document.getElementById("myCanvas") 
+0

更多的信息:https://开头WWW .polymer-project.org/1.0/docs/devguide/local-dom –

+0

你也可以这样做:this。$。myCanvas直接 –