After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas
proved to be ineffective, specifically with regards to the width
attribute. Despite changing the value, the width remained unchanged. While setting maintainAspectRatio
to false and responsive
to true, these adjustments did not resolve the problem.
How can I ensure that the chart fits within the designated width and height?
Any suggestions or advice would be greatly appreciated.
<canvas id="monthly-sales" width="300" height="200"></canvas>
JS
var monthlySales = document.getElementById("monthly-sales").getContext('2d');
var monthlySalesChart = new Chart(monthlySales, {
type: 'bar',
data: {
labels: listOfMonths.slice(10,2),
datasets: [{
label: 'Sales',
data: [
monthlyFees['sales'][10],
monthlyFees['sales'][11]
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 1,
}]
},
options: {
title: {
display: true,
text: 'Sales'
},
legend: {
display: false,
},
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
userCallback: function userCallback(tick) {
return (tick / 100000000);
}
}
}]
},
tooltips: {
callbacks: {
label: function label(tooltipItem, data) {
return numeral(tooltipItem.yLabel).format('0,0');
}
}
}
}
});
Html
<div class="col-sm-12">
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">This month</h4>
</div>
<div class="card-body">
<div class="col-sm-4">
<div class="card-chart">
<canvas id="monthly-sales" width="200" height="200"></canvas>
</div>
<div>
Sales Changed: <span id="monthly-sales-changes"></span>
</div>
</div>
<div class="col-sm-4">
<div class="card-chart">
<canvas id="monthly-profits" width="200" height="150"></canvas>
</div>
</div>
<div class="col-sm-4">
<div class="card-chart">
<canvas id="monthly-orders" width="200" height="150"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>