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

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

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

  1. const connectorLines = {
  2. id: 'connectorLines',
  3. beforeDraw(char, args, options){
  4. const { ctx, config, scales: { x, y } } = myChart;
  5. // ISSUE HERE -> NaN
  6. console.log(x.getPixelForValue('2021-11-07T00:23:35'));
  7. drawArrow(ctx, 128, y.getPixelForValue('C'), 128, y.getPixelForValue('A1') - 4.5, 1, 'rgba(74, 122, 181)');
  8. }
  9. };
  10. const config = {
  11. type: 'bar',
  12. options: {
  13. scales: {
  14. x: {
  15. parsing: false,
  16. position: 'top',
  17. type: 'time',
  18. min: '2021-11-07T00:23:20',
  19. bounds: 'data',
  20. time: {
  21. unit: 'minute'
  22. }
  23. }
  24. },
  25. indexAxis: 'y',
  26. grouped: false,
  27. elements: {
  28. bar: {
  29. borderWidth: 2,
  30. }
  31. },
  32. responsive: true,
  33. plugins: {
  34. legend: {
  35. position: 'right',
  36. }
  37. }
  38. },
  39. data: {
  40. datasets: [{
  41. label: 'S_1',
  42. data:
  43. [
  44. {y:'C', x:['2021-11-07T00:23:35', '2021-11-07T00:23:35'], id: 'id1' },
  45. {y:'A', x:['2021-11-07T00:23:41', '2021-11-07T00:24:20'], id: 'id2'},
  46. {y:'A1', x:['2021-11-07T00:23:35', '2021-11-07T00:23:41'], id: 'id3'}
  47. ],
  48. backgroundColor: [
  49. 'rgba(74, 122, 181)'
  50. ],
  51. borderColor: [
  52. 'rgba(193, 193, 193)'
  53. ],
  54. borderWidth: 1,
  55. borderSkipped: true
  56. }]
  57. },
  58. plugins: [ connectorLines ],
  59. };
xghobddn

xghobddn1#

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

  1. const connectorLines = {
  2. id: 'connectorLines',
  3. beforeDraw(chart, args, options) {
  4. const xAxis = chart.scales.x;
  5. const xValue = new Date('2021-11-07T00:23:35').getTime();
  6. console.log(xAxis.getPixelForValue(xValue));
  7. ...
  8. }
  9. };

相关问题