Chart.js - 无法读取null的属性'getContext'

时间:2015-03-19 01:26:10

标签: javascript charts

我的main.js文件中有以下Javascript:

//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";
      }
    }
  });
}

HTML如下:

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

正如标题所暗示的那样,我得到Uncaught TypeError: Cannot read property 'getContext' of null并且我不完全确定问题是什么。如果我不得不猜测我说它试图引用那些不存在的东西,但我不能100%肯定我是否正确以及如何解决它。任何建议都会很棒。

3 个答案:

答案 0 :(得分:13)

抛出错误的行是

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

据说document.getElementById('winLossChart')不存在。

这是因为在DOM中创建元素之前,您的脚本正在被解释。

您可以在window.onload函数中启动脚本:

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

或者您可以将脚本标记本身作为html文件的body元素中的最后一个元素。

<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 = ...,这会让你更有可能发现问题的根源。

答案 1 :(得分:1)

我遇到了同样的问题。该元素作为dispHTMLUnkownElement返回。

解决方案是将<!DOCTYPE html>添加到我的响应顶部,然后IE正确选择元素类型。

答案 2 :(得分:0)

也许这可以帮助别人...... 你必须使用 destroy()方法 为了使你必须在代码中改变一些东西:

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