javascript - 为什么我不能更新 chartjs 图表中的 aspectRatio?

标签 javascript html css chart.js

如果我尝试更改图表的 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>

最佳答案

an issue在 Chart.js 中关于 chart.options.aspectRatio 的更改未考虑在内。作为解决方法,您可以直接编辑 chart.aspectRatio,然后调用 chart.resize()

function setAspectRatio() {
    myChart.aspectRatio = 9;
    myChart.resize();
}

关于javascript - 为什么我不能更新 chartjs 图表中的 aspectRatio?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58805910/

相关文章:

javascript - 如何获取 Bootstrap File Input 插件创建的图像数据

javascript - 在 react native 矢量图标中按下时如何更改图标名称

html - 2 次要的跨浏览器 CSS 问题。背景图片未在 Google Chrome 中显示?

html - 侧边栏下方的主要内容。 float 不起作用?

html - Bootstrap 导航栏列表下拉列表扩展得太宽

javascript - 简单的响应式图片方法

javascript - 将生成器函数的结果设置在变量中

html - 使用 <a> anchor 元素提交表单,不使用 javascript

javascript - 动态创建或删除表单元素

jquery - 如何在 Bootstrap 日期分页器中只显示一个元素