Javascript Chart.js - 无法读取 null 的属性“getContext”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29135682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:54:23  来源:igfitidea点击:

Chart.js - Cannot read property 'getContext' of null

javascriptcharts

提问by connor martin

I have the following Javascript in my main.jsfile:

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

And the HTML is as follows:

HTML如下:

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

As the title suggests, I am getting Uncaught TypeError: Cannot read property 'getContext' of nulland I'm not entirely sure what the issue is. If I had to guess I'd say it was trying to reference something that wasn't there but I'm not 100% sure on if I am correct and how to fix it. Any advice would be great.

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

回答by Sam Fen

The line that is throwing the error is

抛出错误的行是

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

It is saying that document.getElementById('winLossChart')does not exist.

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

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

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

You could either kick off the script in a window.onloadfunction:

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

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

Or you could put the script tag itself as the last element in the body element of your html file.

或者,您可以将脚本标签本身作为 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>

Either solution would mean that the main entry point of your code (createChartWinLoss) would only happen after the other elements on the page, including the canvas, were created.

这两种解决方案都意味着您的代码 ( createChartWinLoss)的主要入口点只会在页面上的其他元素(包括画布)创建之后发生。

As a general process towards solving these kinds of problems, when you saw the exception in your Javascript console, you should have been able to open the stack trace, which would have led you to the fact that the error originated on the line var winLossChart = ..., which would have made you more likely to have been able to discover the source of the problem.

作为解决此类问题的一般过程,当您在 Javascript 控制台中看到异常时,您应该能够打开堆栈跟踪,这将导致您发现错误起源于该行的事实var winLossChart = ...,这将使您更有可能发现问题的根源。

回答by Howard

I was having this same problem. The element was being returned as dispHTMLUnkownElement.

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

The solution was to add <!DOCTYPE html>to the top of my response and then IE picked up the element type properly.

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

回答by eladolo

Perhaps this can help someone else... You have to use destroy()method.
To made that you have to change a few things in your code:

也许这可以帮助其他人...您必须使用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

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