Reputation: 461
I'm trying to use chart.js to create thumbnails which will link to pages with the full chart.
The full chart on the linked page looks good but the for the thumbnail I just can't get the sizing right. The canvas is covering the right area but the graph doesn't fill it vertically.
var data = {
labels: ['','','','','','','','','',''],
datasets: [{
data:[22,25,23,24,25,22,25,23,24,25],
backgroundColor: "rgba(54, 255, 170, 0.4)",
borderColor: "rgba(54, 255, 170, 1)",
orderWidth: 1,
}]
};
var options = {
tooltips: false,
legend: {
display:false
},
scales: {
yAxes: [{
display:false,
ticks: {
beginAtZero:true
}
}],
xAxes: [{
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}]
}
};
new Chart($("#chart-"+this.model.id), {
type: 'bar',
data: data,
options: options
});
I've tried things like adjusting the min-height of the canvas but that causes the bars to blur. Is there any way I can adjust the height of the bars to occupy the whole canvas?
Upvotes: 13
Views: 36996
Reputation: 4661
Use maintainAspectRatio
and responsive
options: {
responsive: true,
maintainAspectRatio: false,
}
let chart = new Chart('myChart', {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Upvotes: 2
Reputation: 11
const config = {
type: 'bar',
data,
options: {
responsive: true,
maintainAspectRatio: false
}
};
var yourChart= new Chart(
document.getElementById('chartCanvas'),
config
);
});
yourChart.canvas.parentNode.style.height = '480px';
yourChart.canvas.parentNode.style.width = '280px';
Upvotes: 1
Reputation: 7059
Actually in Chart.js 3.2.1 to update the aspect ratio to add more height to your scheme you can use the aspectRatio
option:
options: {
aspectRatio: 1,
}
And so according to the documentation:
Canvas aspect ratio (i.e. width / height, a value of 1 representing a square canvas). Note that this option is ignored if the height is explicitly defined either as attribute or via the style.
You can set it such as:
1
for it to be square0.5
to be twice as high as wide2
to be twice as wide as highUpvotes: 9
Reputation: 316
Try to set these options:
options: {
responsive: true,
maintainAspectRatio: false
}
If you set maintainAspectRatio to true, the height will be automatically calculated.
Upvotes: 30