如何获取日期值的像素?我想画一条线。但对于 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 ],
};
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));
...
}
};
我没用过
getTime()
const drawSelectedRange = {
id: 'drawSelectedRange',
beforeDraw(chart, args, options) {
if (selectedDate1 && selectedDate2) {
const {ctx, chartArea: {left, top, width, height}} = chart;
const xScale = chart.scales["x"];
var xValMin = selectedDate1, xPixelMin = xScale.getPixelForValue(xValMin);
var xValMax = selectedDate2, xPixelMax = xScale.getPixelForValue(xValMax);
ctx.save();
ctx.fillStyle = 'rgba(240, 240, 60, 0.5)'; // yellow
ctx.fillRect(xPixelMin, top, xPixelMax - xPixelMin, height); // x, y, width, height
ctx.restore();
}
}
};