我正在尝试编辑图表,但我做不到。 我想将 Canvas 高度更改为固定高度。图表始终以 1156px X 867 开头。我还需要更改每个条形的高度。
那么,如何更改 Canvas 的大小以及如何更改每个栏的高度。 我有这段代码:
var ctx = document.getElementById("chart");
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: data['labels'],
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: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
html:
<canvas id="chartMentes" width="400" height="300"></canvas>
最佳答案
How can I change the size of canvas?
通常,ChartJS 以响应方式显示图表,这意味着它不会考虑 Canvas 的宽度和高度(由用户设置)。
要解决这个问题,您需要在图表选项中将 responsive
属性设置为 false
,就像这样......
options: {
responsive: false,
...
}
现在,您可以根据需要设置 Canvas 的宽度和高度。
<canvas id="chartMentes" width="400" height="800"></canvas>
How can I change the height of each bar?
您可以通过在图表选项中相应地为 y 轴设置 barThickness
属性来更改每个条形的高度,就像这样......
options: {
scales: {
yAxes: [{
barThickness: 10, //set that suits the best
...
}
ᴅᴇᴍᴏ
var ctx = document.getElementById("chartMentes").getContext('2d');
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
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: false,
scales: {
yAxes: [{
barThickness: 10,
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chartMentes" width="300" height="200"></canvas>
关于javascript - Chart js - 自定义图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44238610/