42 lines
1.4 KiB
JavaScript
42 lines
1.4 KiB
JavaScript
const fillPlugin = {
|
|
id: 'fillHigherValue',
|
|
beforeDatasetsDraw(chart) {
|
|
const { ctx } = chart;
|
|
const metaA = chart.getDatasetMeta(0); // Dataset A
|
|
const metaB = chart.getDatasetMeta(1); // Dataset B
|
|
|
|
ctx.save();
|
|
|
|
// Loop through your data points
|
|
for (let i = 0; i < metaA.data.length; i++) {
|
|
const pA = metaA.data[i];
|
|
const pB = metaB.data[i];
|
|
|
|
if (!pA || !pB) continue;
|
|
|
|
// Define your colors
|
|
const colorA = 'rgba(255, 99, 132, 0.4)'; // Color when Line A is higher
|
|
const colorB = 'rgba(54, 162, 235, 0.4)'; // Color when Line B is higher
|
|
|
|
// Determine which line is higher (remember canvas Y=0 is at the top)
|
|
if (pA.y < pB.y) {
|
|
ctx.fillStyle = colorA;
|
|
} else {
|
|
ctx.fillStyle = colorB;
|
|
}
|
|
|
|
// Draw the fill polygon segment between the two points
|
|
ctx.beginPath();
|
|
ctx.moveTo(pA.x, pA.y);
|
|
ctx.lineTo(pB.x, pB.y);
|
|
// If doing multiple segments, connect back to create a contiguous fill
|
|
if (metaA.data[i + 1] && metaB.data[i + 1]) {
|
|
ctx.lineTo(metaB.data[i + 1].x, metaB.data[i + 1].y);
|
|
ctx.lineTo(metaA.data[i + 1].x, metaA.data[i + 1].y);
|
|
}
|
|
ctx.closePath();
|
|
ctx.fill();
|
|
}
|
|
ctx.restore();
|
|
}
|
|
}; |