Chart.js - Unable to read the 'getContext' property from null

I have the following Javascript in my main.jsfile:

//array object of API stuff

function createChartWinLoss(wins, losses) {

  var pieData = [
    {
      value: losses,
      color: "#F7464A",
      highlight: "#FF5A5E",
      label: "Losses"
    },
    {
      value: wins,
      color: "#46BFBD",
      highlight: "#5AD3D1",
      label: "Wins"
    }
  ];

  var pieOptions = {
    segmentShowStroke : false,
    animateScale : true
  }


  var winLossChart = document.getElementById('winLossChart').getContext('2d');
  new Chart(winLossChart).Pie(pieData, pieOptions);
}

//creates the chart with test data
createChartWinLoss();

function summonerLookUp() {
  var SUMMONER_ID = "";
  var API_KEY = "keyhere";
  var sumID = $("#theKey").val();
  var div = document.getElementById('stuff');
  var combine = "";
  var array = [sumID];
  var wins;
  var losses;

  div.innerHTML = div.innerHTML + "<br />array count: " + array.length + "<br />";
  for (var i = 0; i < array.length; i++) {
    combine = "";
    SUMMONER_ID = array[i];
    getStuff(SUMMONER_ID, combine, API_KEY, div, i);
  }
}

function getStuff(SUMMONER_ID, combine, API_KEY, div, count) {
  var Topuser = SUMMONER_ID;
  $.ajax({
    url: 'https://euw.api.pvp.net/api/lol/euw/v2.5/league/by-summoner/' + SUMMONER_ID + '/entry?api_key=' + API_KEY,
    type: 'GET',
    dataType: 'json',
    async: false,
    data: {},
    success: function (json) {
      var user = Topuser;
      if (typeof json[user][0].queue != "undefined") {
        if (json[user][0].queue == "RANKED_SOLO_5x5") {
          combine = json[user][0].tier + " " + json[user][0].entries[0].division  + " - " + json[user][0].entries[0].wins + " Wins " + json[user][0].entries[0].losses + " losses";
          div.innerHTML = div.innerHTML + "<br />" + count + ": " + user + " " + combine;
          var wins = json[user][0].entries[0].wins;
          var losses = json[user][0].entries[0].losses;
          //populates chart with wins losses from api
          createChartWinLoss(wins,losses);
        }
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      var user = Topuser;
      console.log(errorThrown);
      if (errorThrown === "Not Found") {
        div.innerHTML = div.innerHTML + "<br />" + count + ": " + user + " " + "UNRANKED";
      }
    }
  });
}

And the HTML is as follows:

<div class="container">
  <h2>Wins/Losses</h2>
  <canvas id="winLossChart" width="400" height="200"></canvas>
</div>

As the name implies, I get Uncaught TypeError: Cannot read property 'getContext' of null, and I'm not quite sure what the problem is. If I were to guess, I would say that he tried to refer to something that was not there, but I am not 100% sure if I am right and how to fix it. Any advice would be great.

+4
source share
3 answers

The line that throws the error is

var winLossChart = document.getElementById('winLossChart').getContext('2d');

They say that document.getElementById('winLossChart')does not exist.

This will be because your script is being interpreted before the elements have finished creating in the DOM.

script window.onload:

window.onload = function() {
   createChartWinLoss();
}

script body html .

<body>
  <div class="container">
    <h2>Wins/Losses</h2>
    <canvas id="winLossChart" width="400" height="200"></canvas>
  </div>
  <script src="myscript.js"></script>
</body>

, (createChartWinLoss) , .

, Javascript, , , var winLossChart = ..., , .

+6

. dispHTMLUnkownElement.

, <!DOCTYPE html> , IE .

+1

Maybe this might help someone else ... you should use the destroy () method .
To do this, you need to change a few things in your code:

var winLossChart = "";// Here you make your chart var global
function createChartWinLoss(wins, losses) {
    var pieData = [{
        value: losses,
        color: "#F7464A",
        highlight: "#FF5A5E",
        label: "Losses"
    }, {
        value: wins,
        color: "#46BFBD",
        highlight: "#5AD3D1",
        label: "Wins"
    }];
    var pieOptions = {
        segmentShowStroke: false,
        animateScale: true
    }
    //Here´s the change inside the function where you run destroy().
    if(typeof winLossChart.destroy != "undefined") winLossChart.destroy();
    winLossChart = document.getElementById('winLossChart').getContext('2d');
    new Chart(winLossChart).Pie(pieData, pieOptions);
}
//creates the chart with test data...

https://github.com/chartjs/Chart.js/issues/3231

0
source

All Articles