no gráfico js (4.4.8)
Quero fornecer cores de linha discretas com base em uma linha de base e um valor limite do ponto de dados.
quando eu dou
ctx.createLinearGradient(0, yBaselinePixel, 0, yThresholdPixel);
- quero aplicar cores apenas àquelas partes do segmento de linha (não em todo o segmento de linha) que cruzam a linha de base ou o limite, como segue
exemplo exemplo link de referência
estou usando chart.js 4.4.8 no vue.js 4.2.5
const getGradient = (ctx, chartArea, chart, yBaselinePixel, yThresholdPixel) => {
const normalize = (pixel) => (pixel - chartArea.bottom) / (chartArea.top - chartArea.bottom);
const stopBaseline = normalize(yBaselinePixel);
const stopThreshold = normalize(yThresholdPixel);
const gradient = ctx.createLinearGradient(0, yBaselinePixel, 0, yThresholdPixel);
gradient.addColorStop(0, "#22c55e");
gradient.addColorStop(stopBaseline, "#f9ba4f");
gradient.addColorStop(stopThreshold, "#f59e0b");
gradient.addColorStop(1, "#ef4444");
return gradient;
}
let flushRateGradient;
const flushRateChartData = {
labels: res.data.map(d => d.build_no),
datasets: [
{
label: 'flush rate',
data: new Array(res.data.length).fill(0),
pointRadius: 2,
// borderColor: '#bd7ebe99',
legendColor: '#bd7ebe99',
tension: 0.2,
isShown: true,
borderColor: (context) => { // the gradient approach
const chart = context.chart;
const { ctx, chartArea } = chart;
if (!chartArea) { // on initial chart load
return;
}
if (flushRateGradient) {
return flushRateGradient;
}
const yBaselinePixel = chart.scales.y.getPixelForValue(flushRateBaselineValue);
const yThresholdPixel = chart.scales.y.getPixelForValue(flushRateThresholdValue);
flushRateGradient = getGradient(ctx, chartArea, chart, yBaselinePixel, yThresholdPixel);
return flushRateGradient;
},
/* ?????
HOW TO ADD MULTIPLE COLOR STOP HERE IN SEGMENT APPROACH WITHOUT APPLYING GRADIENT.
AS THIS IS COLORING THE WHOLE LINE SEGMENT WITH ONE COLOR
????? */
// segment: { // the segment approach
// borderColor: ctx => (ctx.p1.parsed.y > flushRateThresholdValue) ? 'red' : '#bd7ebe99',
// }
},
{
label: '', // actual threshold drawn on chart
type: 'line',
data: new Array(res.data.length).fill(flushRateBaselineValue),
pointRadius: 0,
borderColor: '#ea6e6e',
borderDash: [4, 7],
borderWidth: 2,
tension: 0.2,
isShown: true,
},
{
label: '', // actual baseline drawn on chart
type: 'line',
data: new Array(res.data.length).fill(flushRateBaselineValue),
pointRadius: 0,
borderColor: '#f9ba4f',
borderDash: [4, 7],
borderWidth: 2,
tension: 0.2,
isShown: true,
},
],
}