【问题标题】:How to get the length (height) of the vertical bar in Chart.js如何在 Chart.js 中获取竖线的长度(高度)
【发布时间】:2020-04-08 05:14:31
【问题描述】:

我的项目中有一个竖线(我使用chart.js)。我需要知道它的长度/高度(以像素为单位)。我试着像这样得到它:

afterDraw: chart => {      
      var yAxis = chart.scales['y-axis-0'];   
      chart.config.data.datasets[0].data.forEach((value, index) => {
        console.log(Math.round(yAxis.getPixelForValue(value))); 
      });      
    }

但我得到了不正确的值。对于水平条,它可以正常工作(使用var xAxis = chart.scales['x-axis-0'])。 什么问题?怎么做?

【问题讨论】:

    标签: javascript chart.js bar-chart


    【解决方案1】:

    尝试使用 getDatasetMeta() 获取元数据。

    var meta = myChart.getDatasetMeta(0);
    var height = meta.data[0]._model.height;
    

    【讨论】:

    • 每个栏的宽度设置相同。高度未定义
    【解决方案2】:

    y 轴的原点(零值)位于top of the canvas。因此,需要将yAxis.bottom减去通过yAxis.getPixelForValue(value)得到的值如下:

    afterLayout: chart => {      
      var yAxis = chart.scales['y-axis-0']; 
      chart.data.datasets[0].data.forEach(value => {
        console.log(Math.round(yAxis.bottom - yAxis.getPixelForValue(value))); 
      });      
    }
    

    请看下面的示例,看看它是如何工作的(代码来自Chart.js Bar documentation page)。

    new Chart('myChart', {
      type: "bar",
      plugins: [{
        afterLayout: chart => {      
          var yAxis = chart.scales['y-axis-0']; 
          chart.data.datasets[0].data.forEach(value => {
            console.log(Math.round(yAxis.bottom - yAxis.getPixelForValue(value))); 
          });      
        }
      }],
      data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
          label: "My First Dataset",
          data: [65, 59, 80, 81, 56, 55, 40],
          fill: false,
          backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
          borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              min: 0,
              stepSize: 20
            }
          }]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
    <canvas id="myChart" height="90"></canvas>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-14
      • 2018-09-18
      • 2023-03-20
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      相关资源
      最近更新 更多