Search code examples
javascriptcanvaspolymerchart.js

Chart js, Canvas is null polymer project


I am working on a polymer project and still figuring my way around. I am trying to use chart js and have tried multiple things and looked up online on other questions but nothing helped me, so I had to ask for some pointers or where can I look to solve my issue.

Its a polymer project I am working on and the html file I am working on has the following structure:

<link rel="import" href="../bower_components/iron-list/iron-list.html">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>



<dom-module id="sensors-app">
    <template>
        <style>
        </style>
        <div>
            <canvas id="chart"></canvas>
        </div>

        <app-header-layout fullbleed>
            </app-header>

            <iron-list onload="myFunction()" id="list" items="[[sensorDataModel]]" as="item" scroll-target="document">
                <template>
                    <div>
                    </div>
                </template>
            </iron-list>

        </app-header-layout>

    </template>

    <script>
       var ctx = document.getElementById("chart").getContext("2d");

        class SensorsApp extends Polymer.Element {

            static get is() { return 'sensors-app'; }

            static get properties() {
                return {
                    sensorDataModel: {
                        type: Array,
                        value: [],
                    }
                };
            }

            // rest of the code
        }

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

Its a school project and I am trying to understand if error is happening because I am putting canvas at the wrong place or some thing else that I don't understand. Any help will be highly appreciated. I removed the code but kept the structure because it would have been quite lengthy otherwise to post here. I am so sorry if I am asking a stupid question, I have worked with backend mostly and this came out of the blue and just want to learn, I hardly managed my way around javascript in such short time, I hope i can get some ideas what I am doing wrong that canvas is always null. This is the error by the way I get:

sensors-app.html:142 Uncaught TypeError: Cannot read property 'getContext' of null

Solution

  • You can get the element in ready method of polymer class so that by the time ready is called, element will be defined and it won't be null. You can use below code

      class SensorsApp extends Polymer.Element {
    
    
        ready(){
        super.ready();
        var ctx = this.shadowRoot.querySelector("#chart").getContext("2d");
        }
        }