简体   繁体   English

如何在 Chart.js 中调整图表的大小/比例

[英]How to size/scale a chart in Chart.js

I use chart.js in my code.我在我的代码中使用 chart.js。 Basically, it works well, but I have an issue with creating nth time a chart in the same canvas. I got error message telling me that I suppose to destroy chart first.基本上,它运行良好,但我在同一个 canvas 中创建第 n 次图表时遇到问题。我收到错误消息,告诉我我想先销毁图表。 Then I found here some ideas how to do this and adapted this part of code as a solution:然后我在这里找到了一些如何做到这一点的想法并将这部分代码改编为解决方案:

let chartStatus = Chart.getChart("line-chart"); 
if (chartStatus != undefined) {
    chartStatus.destroy();
    //$("div.line-chart").remove();
    //$("div.line-chart").append('<canvas id="line-chart" style="width: 1221px; height: 280px;"></canvas>');
}

It works fine - at least I do not get any errors any more, but when I create chart for second and more times, it gets resized.它工作正常 - 至少我不再收到任何错误,但是当我第二次和更多次创建图表时,它会调整大小。 Please look at the attached pictures:请看附图: 第一次使用图表...

第二次图表使用...

If you look at the scale you notice it is changed.如果您查看秤,您会发现它发生了变化。

My question is: How can I destroy a chart and recreate its size/scale etc correctly or how can I update a chart instead of destroying it?我的问题是:如何销毁图表并正确地重新创建其大小/比例等,或者如何更新图表而不是销毁它?

The code looks like this:代码如下所示:

javascript: javascript:

let chartStatus = Chart.getChart("line-chart"); 
if (chartStatus != undefined) {
    chartStatus.destroy();
    //$("div.line-chart").remove();
    //$("div.line-chart").append('<canvas id="line-chart" style="width: 1221px; height: 280px;"></canvas>');
}

new Chart(document.getElementById("line-chart"), {
    type: 'line',
    data: {
            labels: labelX,
            datasets: [{ 
            data: waga,
                label: "Waga",
                borderColor: "#3e95cd",
                borderWidth: 1,
                fill: false
        }
        ]
    },
    options: {
            title: {
            display: true,
            responsive: true,
            maintainAspectRatio: false
        }
    }
});

HTML: HTML:

<div><canvas id="line-chart" style="width: 1221px; height: 280px;"></canvas></div>

I have found a solution that works for me here .我在这里找到了适合我的解决方案。 Now, my code looks like this:现在,我的代码如下所示:

let chartStatus = Chart.getChart("line-chart"); 
if (chartStatus != undefined) {
    document.getElementById('line-chart').remove();
    let canvas = document.createElement('canvas');     
    canvas.setAttribute('id','line-chart');     
    canvas.setAttribute('width','1221');     
    canvas.setAttribute('height','280');     
    document.querySelector("#line-chart-wrapper").appendChild(canvas);
}

and HTML part...和 HTML 部分...

<div id="line-chart-wrapper"><canvas id="line-chart" style="width: 1221px; height: 280px;"></canvas></div>

Now chart looks OK no matter how many times it is created.现在,无论创建多少次,图表看起来都不错。

The canvas will get resized each time the chart is drawn, to accommodate the contents of the chart.每次绘制图表时,canvas 都会调整大小,以适应图表的内容。 It could be done the other way around - to accommodate the contents to the size, but that's a complicated and time consuming, and will not always work ok if the sizes are very unequal, so chart.js chooses to adjust the size.也可以反其道而行之——根据大小调整内容,但这既复杂又耗时,而且如果大小非常不相等,也不一定能正常工作,因此 chart.js 选择调整大小。

Therefore you cannot count on the styled size of the canvas, so it is recommended to style the size of the container div, like in the following example, loosely based on your code excerpt.因此,您不能指望 canvas 的样式大小,因此建议为容器 div 的大小设置样式,如下例所示,大致基于您的代码摘录。

 let labelX = [], waga = []; function resetData(){ const d0 = Date.now() - 3*365*24*3600*1000*Math.random(); // change the whole arrays, since the chart is destroyed and rebuilt labelX = Array.from({length: 10}, (_, i) => new Date(d0 + i * 24 * 3600 * 1000).toLocaleDateString(undefined, {year: 'numeric', month: 'numeric', day: 'numeric'})); waga = Array.from({length: 10}, (_, i) => Math.random()); } let chart; function drawChart(){ chart = new Chart(document.getElementById("line-chart"), { type: 'line', data: { labels: labelX, datasets: [{ data: waga, label: "Waga", borderColor: "#3e95cd", borderWidth: 1, fill: false }] }, options: { title: { display: true, responsive: true, maintainAspectRatio: false }, scales: { x: { bounds: 'ticks', type: 'category', }, y: { type: 'linear', display: true, min: 0, max: 1 } } } }); } resetData(); drawChart(); document.getElementById('reset').onclick = function(){ resetData(); document.querySelector('canvas#line-chart').innerHTML = ''; chart.destroy(); drawChart(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.2/chart.umd.js" integrity="sha512-t41WshQCxr9T3SWH3DBZoDnAT9gfVLtQS+NKO60fdAwScoB37rXtdxT/oKe986G0BFnP4mtGzXxuYpHrMoMJLA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <div id="line-chart-container" style="height:300px; border: 1px solid red"> <canvas id="line-chart"></canvas> </div> <button id="reset">Reset</button>

Still, the more efficient solution would be to just change the data and then call chart.update , if it fits your purpose, like this:尽管如此,更有效的解决方案是仅更改数据然后调用chart.update ,如果它符合您的目的,如下所示:

 const labelX = [], waga = []; function resetData(){ const d0 = Date.now() - 3*365*24*3600*1000*Math.random(); // using splice 0 to infinity to replace all data *inside* the arrays labelX.splice(0, 1/0, ...Array.from({length: 10}, (_, i) => new Date(d0 + i * 24 * 3600 * 1000).toLocaleDateString(undefined, {year: 'numeric', month: 'numeric', day: 'numeric'}))); waga.splice(0, 1/0, ...Array.from({length: 10}, (_, i) => Math.random())); } resetData(); const chart = new Chart(document.getElementById("line-chart"), { type: 'line', data: { labels: labelX, datasets: [{ data: waga, label: "Waga", borderColor: "#3e95cd", borderWidth: 1, fill: false }] }, options: { title: { display: true, responsive: true, maintainAspectRatio: false }, scales: { x: { bounds: 'ticks', type: 'category', }, y: { type: 'linear', display: true, min: 0, max: 1 } } } }); document.getElementById('reset').onclick = function(){ resetData(); chart.update(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.2/chart.umd.js" integrity="sha512-t41WshQCxr9T3SWH3DBZoDnAT9gfVLtQS+NKO60fdAwScoB37rXtdxT/oKe986G0BFnP4mtGzXxuYpHrMoMJLA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <body> <div id="line-chart-container" style="height:300px; border: 1px solid red"> <canvas id="line-chart"></canvas> </div> <button id="reset">Reset</button> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM