-
Beta Was this translation helpful? Give feedback.
Answered by
char101
Sep 12, 2024
Replies: 1 comment 1 reply
-
It is called clipping. You draw your first line as a closed path (including the area below it), the second path as another closed path (including the area above it), then fill the first path using the second path as clip. // create path object for filling and clipping
export function createAreaPath(xs, ys, y) {
const p = new Path2D();
if (xs.length > 1) {
p.moveTo(xs[0], y);
for (let i = 0, n = xs.length; i < n; ++i) {
p.lineTo(xs[i], ys[i]);
}
p.lineTo(xs[xs.length - 1], y);
}
return p;
}
// fill area where y1 > y2 with color
export function fillPathBetween(ctx, xs, y1, y2, color) {
if (xs.length === 0) return;
const canvas = ctx.canvas;
ctx.save();
ctx.fillStyle = color;
ctx.clip(createAreaPath(xs, y1, canvas.height));
ctx.fill(createAreaPath(xs, y2, 0));
ctx.restore();
} This is an example indicator where you draw a difference between two moving averages as a shade import {fillPathBetween} from '../utils.js';
export default {
draw: ({ctx, kLineDataList, indicator, visibleRange, bounding, xAxis, yAxis}) => {
const result = indicator.result;
if (!result) return;
const {from, to} = visibleRange;
const timeScaleStore = xAxis.getParent().getChart().getChartStore().getTimeScaleStore();
const xs = [];
const y1 = [];
const y2 = [];
for (let i = from; i < to; ++i) {
const ind = result[i];
if (ind) {
xs.push(timeScaleStore.dataIndexToCoordinate(i));
y1.push(yAxis.convertToPixel(ind.fast));
y2.push(yAxis.convertToPixel(ind.slow));
}
}
fillPathBetween(ctx, xs, y1, y2, '#50C87880');
fillPathBetween(ctx, xs, y2, y1, '#CC397B80');
return true;
},
}; |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
asfand987
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is called clipping. You draw your first line as a closed path (including the area below it), the second path as another closed path (including the area above it), then fill the first path using the second path as clip.