如何在ChartJs中获取时间值的像素来画线?

piwo6bdm  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(161)

如何获取日期值的像素?我想画一条线。但对于x轴,我有时间值。因此我无法获取x的像素。我尝试使用getPixelForValue。但它返回NaN。我需要获取确切的值来画一条线。

const connectorLines = {
    id: 'connectorLines',
    beforeDraw(char, args, options){
        const { ctx, config, scales: { x, y } } = myChart;

        // ISSUE HERE -> NaN
        console.log(x.getPixelForValue('2021-11-07T00:23:35'));
        drawArrow(ctx, 128, y.getPixelForValue('C'), 128, y.getPixelForValue('A1') - 4.5, 1, 'rgba(74, 122, 181)');
    }
};

const config = {
    type: 'bar',
    options: {  
         scales: { 
             x: {
                parsing: false,
                position: 'top',
                type: 'time',
                min: '2021-11-07T00:23:20',
                bounds: 'data',
                time: {
                    unit: 'minute'
                }
             } 
         }, 
        indexAxis: 'y',
        grouped: false,
        elements: {
          bar: {
            borderWidth: 2,
          }
        },
        responsive: true,
        plugins: {
          legend: {
            position: 'right',
          }
        }
      },
        data: {
          datasets: [{
            label: 'S_1',
            data: 
                [
                    {y:'C', x:['2021-11-07T00:23:35', '2021-11-07T00:23:35'], id: 'id1' },
                    {y:'A', x:['2021-11-07T00:23:41', '2021-11-07T00:24:20'], id: 'id2'}, 
                    {y:'A1', x:['2021-11-07T00:23:35', '2021-11-07T00:23:41'], id: 'id3'}
                ],
                backgroundColor: [
                  'rgba(74, 122, 181)'
                ],
                borderColor: [
                  'rgba(193, 193, 193)'
                ],
                borderWidth: 1,
                borderSkipped: true
          }]
        },
        plugins: [ connectorLines ],
};
xghobddn

xghobddn1#

Chart.js将x轴上的日期转换为表示时间的数字。因此,在调用getPixelForValue之前,还需要使用Date.getTime()将特定日期转换为时间,如下所示。

const connectorLines = {
    id: 'connectorLines',
    beforeDraw(chart, args, options) {
        const xAxis = chart.scales.x;
        const xValue = new Date('2021-11-07T00:23:35').getTime();
        console.log(xAxis.getPixelForValue(xValue));
        ...
    }
};

相关问题