ChartJS 2 - 在添加 X 项后向图表中断添加数据

ChartJS 2 - Adding data to chart breaks after X number of items added

我正在使用 Chart.js 2.6。我在创建图表后添加数据,以便我可以在图表容器上创建一个 overflow-x。

例子here.

问题是,在我的示例中,如果您将 for 循环从 532 更改为 531 或更少,图表可以正常呈现。但是,当计数为 532 或更高时,图表不会抛出任何错误,但它是空白的。我不确定是什么原因造成的。

任何人都可以看看它可能是什么?这似乎与我在每次迭代中增加 chartAreaWrapper2 div 宽度的方式有关,但我不明白为什么。

JS

var ctx = document.getElementById("myChart").getContext("2d");

var chart = {
    options: {
        responsive: true,
        maintainAspectRatio: false,
        animation: {

            onComplete: function(animation) {
                var sourceCanvas = myLiveChart.chart.canvas;
                var copyWidth = myLiveChart.scales['y-axis-0'].width - 10;
                var copyHeight = myLiveChart.scales['y-axis-0'].height + myLiveChart.scales['y-axis-0'].top + 10;
                var targetCtx = document.getElementById("myChartAxis").getContext("2d");
                targetCtx.canvas.width = copyWidth;
        targetCtx.drawImage(sourceCanvas, 0, 0, copyWidth, copyHeight, 0, 0, copyWidth, copyHeight);
            }
        }
    },
    type: 'bar',
    data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        }]
    }
};

var myLiveChart = new Chart(ctx, chart);


for(x=0;x<532;x++) {
    myLiveChart.data.datasets[0].data.push(Math.random() * 100);
    myLiveChart.data.labels.push("Test");
    var newwidth = $('.chartAreaWrapper2').width() + 60;
    $('.chartAreaWrapper2').width(newwidth);
}

HTML

<div class="chartWrapper">
    <div class="chartAreaWrapper">
        <div class="chartAreaWrapper2">
            <canvas id="myChart"></canvas>
        </div>
    </div>

    <canvas id="myChartAxis" height="300" width="0"></canvas>
</div>

CSS

.chartWrapper {
    position: relative;
}

.chartWrapper > canvas {
    position: absolute;
    left: 0;
    top: 0;
    pointer-events:none;
}

.chartAreaWrapper {
    overflow-x: scroll;
    position: relative;
    width: 100%;
}

.chartAreaWrapper2 {
    position: relative;
    height: 300px;
}

<canvas> 元素有最大宽度。在 Chrome 和 Firefox 中,最大值为 32,767 像素。有关 <canvas> 元素在不同浏览器中的最大宽度的更多详细信息,请参阅 this answer

我更新了 JSFiddle 以使用当前 canvas 宽度作为新标签,而不仅仅是 "Test"。如果你设置循环迭代531次,你看最后一个label是32676,此时canvas基本达到了最大宽度。当您尝试超过 531 时,宽度达到超过最大允许宽度的数字,因此 canvas 对象不会呈现。