Search code examples
javascripthtmlcanvaspolymer

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


I want to draw a shape on a canvas inside my Polymer Element. The problem is that I run the canvas drawing code before I initialise my custom Element. I tried the ready function, but it is still not working.

Here is the Code of my 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>

If I run this Code there appears a error saying:

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)

Is it possible to draw on a canvas inside a Polymer Element? I'm new to Polymer and I don't have much experience.


Solution

  • document.getElementById is for accessing element ouside your dom. you need to use this.$ to get the element

    to get the canvas by is you can use:

    this.$["myCanvas"]
    

    instead of:

    document.getElementById("myCanvas")