首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ChartJ中获得时间值的像素来绘制一条线?

问如何在ChartJ中获得时间值的像素来绘制一条线?
EN

Stack Overflow用户
提问于 2022-08-22 19:33:47
回答 1查看 54关注 0票数 0

如何获得日期值的像素?我想划一条线。但是对于x轴,我有时间值。因为它,我不能提取x的像素。我正在尝试使用getPixelForValue。但是它返回NaN。我需要精确的数值来画一条线。

代码语言:javascript
复制
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 ],
};
EN

回答 1

Stack Overflow用户

发布于 2022-08-23 06:33:22

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

代码语言:javascript
复制
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));
        ...
    }
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73450201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档