2017-10-07 3 views
1

Ich möchte eine Form auf einer Leinwand in meinem Polymer Element zeichnen. Das Problem ist, dass ich den Canvas-Zeichnungscode ausführe, bevor ich mein benutzerdefiniertes Element initialisiere. Ich habe versucht, die ready Funktion, aber es funktioniert immer noch nicht.Ist es möglich, auf einer Leinwand in einem Element zu zeichnen?

Hier ist der Code meines Element:

<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> 

Wenn ich diesen Code ausführen scheint ein Fehler zu sagen:

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) 

Ist es möglich, in einem Polymerelement auf einer Leinwand zu zeichnen? Ich bin neu in Polymer und ich habe nicht viel Erfahrung.

Antwort

2

document.getElementById ist für den Zugriff auf das Element außerhalb Ihres Doms. Sie müssen diese verwenden $ das Element erhalten

die Leinwand zu erhalten, indem die Sie verwenden können.

this.$["myCanvas"] 

statt:

document.getElementById("myCanvas") 
+0

weitere Informationen: https: // www .polymer-project.org/1.0/docs/devguide/local-dom –

+0

können Sie auch: this. $. myCanvas direkt –

Verwandte Themen