If I set height with style attribute for chart div
<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
chart is looking like that (chart is displayed below canvas):
JavaScript
x
41
41
1
var barChartData = {
2
labels: [""],
3
datasets: [{
4
label: "1",
5
backgroundColor: "rgba(68,222,166,1)",
6
barThickness: 50,
7
data: [177]
8
},
9
{
10
label: "2",
11
barThickness: 50,
12
backgroundColor: "rgba(218, 65, 102, 1)",
13
data: [170]
14
}
15
]
16
};
17
18
var optionsBar = {
19
legend: false,
20
title: {
21
display: false
22
},
23
scales: {
24
xAxes: [{
25
stacked: true,
26
display: false
27
}],
28
yAxes: [{
29
stacked: true,
30
display: false
31
}]
32
}
33
};
34
35
36
var ctx = document.getElementById("chart");
37
var myChart = new Chart(ctx, {
38
type: 'horizontalBar',
39
data: barChartData,
40
options: optionsBar
41
});
JavaScript
1
5
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
2
3
<body style="background-color: grey;">
4
<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
5
</body>
How to fix that?
Advertisement
Answer
It’s showing like this because canvas’s aspect ratio is changing automatically with window size but you’ve set your div to a specific height of 100px
. That’s why canvas has placed outside of the div while window size is extending. Just to get rid of that problem, set maintainAspectRatio: false
in your option in this way:
JavaScript
1
42
42
1
var barChartData = {
2
labels: [""],
3
datasets: [{
4
label: "1",
5
backgroundColor: "rgba(68,222,166,1)",
6
barThickness: 50,
7
data: [177]
8
},
9
{
10
label: "2",
11
barThickness: 50,
12
backgroundColor: "rgba(218, 65, 102, 1)",
13
data: [170]
14
}
15
]
16
};
17
18
var optionsBar = {
19
maintainAspectRatio: false,
20
legend: false,
21
title: {
22
display: false
23
},
24
scales: {
25
xAxes: [{
26
stacked: true,
27
display: false
28
}],
29
yAxes: [{
30
stacked: true,
31
display: false
32
}]
33
}
34
};
35
36
37
var ctx = document.getElementById("chart");
38
var myChart = new Chart(ctx, {
39
type: 'horizontalBar',
40
data: barChartData,
41
options: optionsBar
42
});
JavaScript
1
5
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
2
3
<body style="background-color: grey;">
4
<div id="chartDiv" style="height: 100px; border: 1px solid red;"><canvas id="chart"></canvas></div>
5
</body>