TypeError:无法读取属性' currentStyle'在chart.js中为null

时间:2017-07-20 19:01:13

标签: chart.js

我每次修改输入字段时都尝试更新我的饼图(使用Chart.js)。我这样做是通过用空画布替换现有图形然后重绘它。这是有效的,但导致我得到一个" TypeError:无法读取属性' currentStyle' of null"。

代码如下,

function drawSummaryPie() {
$('#myChart').replaceWith('<canvas id="myChart" width="200" height="200"></canvas>');
draw(); 
}[enter image description here][1]   

错误:enter image description here

任何帮助将不胜感激!

4 个答案:

答案 0 :(得分:3)

HTML:

<div id="line_chart" style="padding-bottom: 20px;">               
 <canvas id="chartJSContainer" height="100"></canvas>
</div>

JS:

$('#chartJSContainer').remove();
$('#line_chart').html('<canvas id="chartJSContainer" height="100"></canvas>'); 
var linectxx = document.getElementById('chartJSContainer').getContext('2d');
var newlinechart = new Chart(linectxx, options1);

它为我工作。使用.html()代替.append:)

答案 1 :(得分:0)

我解决了将画布放在div中的问题,例如:

<div style="width:75%;">
    <canvas id="canvas"></canvas>
</div>

或在JS中:

var div = document.createElement('div');
div.style = "width:100%;";
canvas = document.createElement('canvas');
div.appendChild(canvas);

答案 2 :(得分:0)

Marcio Rossato的解决方案对我不起作用,但是这个解决方案对我有用:

在此处查看Valentin的答案:Solution for "Cannot read property 'currentStyle' of null in ChartJS"

我下载并修改了文件,现在没有错误:)

答案 3 :(得分:0)

这种情况可能是由多种因素造成的。
也就是说,就我而言,这是由于没有销毁我的代码已实例化的先前图表实例造成的。

当您调整浏览器窗口大小时,Chart JS 会自动绑定一个事件来处理图表的调整大小。当您在不破坏旧对象或刷新页面的情况下用新图表替换旧图表时,先前设置的事件会继续侦听和执行,指向不再存在引用的元素,从而导致尝试从不再存在的对象。

因此,要解决此问题,您必须在替换之前使用正确的方法销毁图表。
示例:

var myChart;
function loadMyChart() {
    if(myChart) myChart.destroy(); // Destroys the previous chart, if it exists.
    
    $('#myChart').replaceWith('<canvas id="myChart"></canvas>');

    $.get("/MyBackEnd/GetMyChart?param1=" + $("#param1").val(), function (data) {
        myChart = new Chart(document.getElementById("myChart"), myChartOptions);
    });
}