Reputation: 41
My charts that I made with chart.js grow each time when I redraw them and I have no idea why. 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:
width: 45%;
padding: 20px 20px;
border-bottom: 1px solid #dedede;
CSS after I run createChart:
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.
Upvotes: 4
Views: 782
Reputation: 3085
It seems like the library you’re using (chart.js) is overriding those css values by default.
One option is to set those values back to their correct values at the end of createChart function.
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.
Upvotes: 2