简体   繁体   English

重绘时Chart.js的画布和图表宽度将被覆盖

[英]Chart.js canvas and chart width gets overwritten when redrawn

My charts that I made with chart.js grow each time when I redraw them and I have no idea why. 每当我重绘图表时,使用chart.js制作的图表都会增长,我也不知道为什么。 My code for the chart cavas is: 我的图表图表代码为:

 let tempChart = document.getElementById("tempChart").getContext('2d'); let pressureChart = document.getElementById("pressureChart").getContext('2d'); let O3Chart = document.getElementById("O3Chart").getContext('2d'); let PM1Chart = document.getElementById("PM1Chart").getContext('2d'); 
 <canvas id="tempChart"></canvas> <canvas id="pressureChart"></canvas> <canvas id="O3Chart"></canvas> <canvas id="PM1Chart"></canvas> 

This is the code I call each time when I want to draw or redraw a chart: 这是我每次要绘制或重绘图表时调用的代码:

 function createChart(chartLabels, chartData, chart, label, backgroundcolor, beginAtZero, borderColor) { let LineChart = new Chart(chart, { type: 'line', data: { labels: chartLabels, datasets: [{ label: label, data: chartData, backgroundColor: backgroundcolor, pointRadius: 0, borderColor: borderColor }] }, options: { responsive: false, scales: { yAxes: [{ ticks: { beginAtZero: beginAtZero } } ] } } }) } 

The CSS of the canvas before I run createChart once: 一次运行createChart之前,画布的CSS:

  width: 45%; padding: 20px 20px; border-bottom: 1px solid #dedede; 

CSS after I run createChart: 运行createChart之后的CSS:

  display: block; height: 341px; width: 683px; 

I have tested this code with empty and full arrays for my labels and data and in both instances the chart grows each time I call the createChart function. 我已经用我的标签和数据的空数组和完整数组测试了此代码,并且在这两种情况下,每次调用createChart函数时,图表都会增长。

It seems like the library you're using (chart.js) is overriding those css values by default. 似乎您正在使用的库(chart.js)默认情况下覆盖了这些CSS值。

One option is to set those values back to their correct values at the end of createChart function. 一种选择是在createChart函数末尾将这些值重新设置为正确的值。

For example: 例如:

tempChart.style.width = 45%;

Other option is add a high power to them in a stylesheet, !important , but this depends on the way (chart.js) is acting. 另一个选择是在样式表!important为它们添加强大的功能,但这取决于(chart.js)的行为方式。

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

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