如果我尝试更改图表的AspectRatio,则无法这样做。此页面还指示应该可以。 https://www.chartjs.org/docs/latest/developers/updates.html
我尝试过的是在这支笔上看到的。 https://codepen.io/snowflakemelter/pen/WNNKKvG
javascript,css,html。按此顺序,您将在下面找到代码。
//works not
function setAspectRatio(){
myChart.options.aspectRatio = 2;
myChart.update();
}
setAspectRatio()
//works
function setChartLabels(){
myChart.data.datasets[0].label = "whatEver";
myChart.update();
}
setChartLabels()
.box{
width: 500px;
}
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.2/dist/Chart.min.js"></script>
</head>
<body>
<div class="box">
<canvas id="myChart"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [ 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [5, 2, 3],
backgroundColor: [
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
aspectRatio: 1,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</div>
</body>
</html>
答案 0 :(得分:0)
Chart.js中有an issue关于chart.options.aspectRatio
上的更改未考虑在内。解决方法是,您可以直接编辑chart.aspectRatio
,然后调用chart.resize()
。
function setAspectRatio() {
myChart.aspectRatio = 9;
myChart.resize();
}