Demonstrates how to split lines into multiple segments so they can be individually colored according to thresholds, using SciChart.js, High Performance JavaScript Charts. This uses a RenderDataTransform to calculate the intersections between the data and the thresholds and add additional points.
import {
BaseRenderableSeries,
BaseRenderDataTransform,
DefaultPaletteProvider,
ECoordinateMode,
EHorizontalAnchorPoint,
EllipsePointMarker,
EStrokePaletteMode,
EVerticalAnchorPoint,
FastLineRenderableSeries,
HorizontalLineAnnotation,
IPointMetadata,
IPointSeries,
MouseWheelZoomModifier,
NativeTextAnnotation,
NumberRange,
NumericAxis,
ObservableArrayBase,
ObservableArrayChangedArgs,
parseColorToUIntArgb,
RenderPassData,
SciChartJsNavyTheme,
SciChartSurface,
TSciChart,
vectorToArrayViewF64,
XyDataSeries,
XyPointSeriesResampled,
ZoomExtentsModifier,
ZoomPanModifier,
DoubleVectorProvider,
} from "scichart";
import { appTheme } from "./appTheme";
class ThresholdRenderDataTransform extends BaseRenderDataTransform<XyPointSeriesResampled> {
public thresholds: ObservableArrayBase<number> = new ObservableArrayBase();
public constructor(parentSeries: BaseRenderableSeries, wasmContext: TSciChart, thresholds: number[]) {
super(parentSeries, wasmContext, [parentSeries.drawingProviders[0]]);
this.thresholds.add(...thresholds);
this.onThresholdsChanged = this.onThresholdsChanged.bind(this);
this.thresholds.collectionChanged.subscribe(this.onThresholdsChanged);
}
private onThresholdsChanged(data: ObservableArrayChangedArgs) {
this.requiresTransform = true;
if (this.parentSeries.invalidateParentCallback) {
this.parentSeries.invalidateParentCallback();
}
}
public delete(): void {
this.thresholds.collectionChanged.unsubscribeAll();
super.delete();
}
protected createPointSeries(): XyPointSeriesResampled {
return new XyPointSeriesResampled(this.wasmContext, new NumberRange(0, 0));
}
protected runTransformInternal(renderPassData: RenderPassData): IPointSeries {
const numThresholds = this.thresholds.size();
if (numThresholds === 0) {
return renderPassData.pointSeries;
}
const { xValues: oldX, yValues: oldY, indexes: oldI, resampled } = renderPassData.pointSeries;
const iStart = resampled ? 0 : renderPassData.indexRange.min;
const iEnd = resampled ? oldX.size() - 1 : renderPassData.indexRange?.max;
// Create views over the source and target vectors for fast access. These views are only valid as long as there is no memory allocation
const oldXView = vectorToArrayViewF64(oldX, this.wasmContext);
const oldYView = vectorToArrayViewF64(oldY, this.wasmContext);
const oldIndexView = vectorToArrayViewF64(oldI, this.wasmContext);
// We do not know the number of output points, so we cannot fast write to views on the output. Instead we write to temporary arrays and then fast append them to the output
const xout: number[] = [];
const yout: number[] = [];
const iout: number[] = [];
// This is the index of the threshold we are currently under.
let level = 0;
let lastY = oldXView[iStart];
// Find the starting level
for (let t = 0; t < numThresholds; t++) {
if (lastY > this.thresholds.get(t)) {
level++;
}
}
let lastX = oldXView[iStart];
xout.push(lastX);
yout.push(lastY);
iout.push(0);
let newI = 0;
for (let i = iStart + 1; i <= iEnd; i++) {
const y = oldYView[i];
const x = oldXView[i];
if (level > 0 && lastY > this.thresholds.get(level - 1)) {
if (y === this.thresholds.get(level - 1)) {
// decrease level but don't add a point
level--;
}
while (y < this.thresholds.get(level - 1)) {
// go down
const t = this.thresholds.get(level - 1);
// interpolate to find intersection
const f = (lastY - t) / (lastY - y);
const xNew = lastX + (x - lastX) * f;
newI++;
xout.push(xNew);
yout.push(t);
// use original data index so metadata works
iout.push(i);
// potentially push additional data to extra vectors to identify threshold level
console.log(lastX, lastX, x, y, t, f, xNew);
level--;
if (level === 0) break;
}
}
if (level < numThresholds && lastY <= this.thresholds.get(level)) {
if (y === this.thresholds.get(level)) {
// increase level but don't add a point
level++;
}
while (y > this.thresholds.get(level)) {
// go up
const t = this.thresholds.get(level);
const f = (t - lastY) / (y - lastY);
const xNew = lastX + (x - lastX) * f;
newI++;
xout.push(xNew);
yout.push(t);
iout.push(i);
console.log(lastX, lastX, x, y, t, f, xNew);
level++;
if (level === numThresholds) break;
}
}
lastY = y;
lastX = x;
newI++;
xout.push(lastX);
yout.push(lastY);
iout.push(newI);
}
const { xValues, yValues, indexes } = this.pointSeries;
// Clear the destination vectors and fast append the result
xValues.clear();
yValues.clear();
indexes.clear();
const dvp = new DoubleVectorProvider();
dvp.appendArray(this.wasmContext, xValues, xout);
dvp.appendArray(this.wasmContext, yValues, yout);
dvp.appendArray(this.wasmContext, indexes, iout);
return this.pointSeries;
}
}
const colorNames = [appTheme.MutedTeal, appTheme.MutedBlue, appTheme.MutedOrange, appTheme.MutedRed];
const colors = colorNames.map((c) => parseColorToUIntArgb(c));
class ThresholdPaletteProvider extends DefaultPaletteProvider {
strokePaletteMode = EStrokePaletteMode.SOLID;
lastY: number;
public thresholds: number[];
public override get isRangeIndependant(): boolean {
return true;
}
public constructor(thresholds: number[]) {
super();
this.thresholds = thresholds;
}
overrideStrokeArgb(
xValue: number,
yValue: number,
index: number,
opacity: number,
metadata: IPointMetadata
): number {
if (index == 0) {
this.lastY = yValue;
}
for (let i = 0; i < this.thresholds.length; i++) {
const threshold = this.thresholds[i];
if (yValue <= threshold && this.lastY <= threshold) {
this.lastY = yValue;
//console.log(index, yValue, i);
return colors[i];
}
}
this.lastY = yValue;
//console.log(index, yValue, this.thresholds.length);
return colors[this.thresholds.length];
}
}
export const drawExample = async (rootElement: string | HTMLDivElement) => {
const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme(),
});
// sciChartSurface.debugRendering = true;
const xAxis = new NumericAxis(wasmContext, {
growBy: new NumberRange(0.025, 0.025),
});
sciChartSurface.xAxes.add(xAxis);
const yAxis = new NumericAxis(wasmContext, {
growBy: new NumberRange(0.05, 0.05),
});
sciChartSurface.yAxes.add(yAxis);
const lineSeries = new FastLineRenderableSeries(wasmContext, {
pointMarker: new EllipsePointMarker(wasmContext, {
stroke: "black",
strokeThickness: 0,
fill: "black",
width: 10,
height: 10,
}),
dataLabels: {
style: {
fontFamily: "Arial",
fontSize: 10,
},
color: "white",
},
strokeThickness: 5,
});
sciChartSurface.renderableSeries.add(lineSeries);
const thresholds = [1.5, 3, 5];
const transform = new ThresholdRenderDataTransform(lineSeries, wasmContext, thresholds);
lineSeries.renderDataTransform = transform;
const paletteProvider = new ThresholdPaletteProvider(thresholds);
lineSeries.paletteProvider = paletteProvider;
const dataSeries = new XyDataSeries(wasmContext, {
xValues: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
yValues: [0, 0.8, 2, 3, 6, 4, 1, 1, 7, 5, 4],
});
lineSeries.dataSeries = dataSeries;
const makeThresholdAnnotation = (i: number) => {
const thresholdAnn = new HorizontalLineAnnotation({
isEditable: true,
stroke: colorNames[i + 1],
y1: thresholds[i],
showLabel: true,
strokeThickness: 3,
axisLabelFill: colorNames[i + 1],
});
thresholdAnn.dragDelta.subscribe((args) => {
if (
(i < colorNames.length - 2 && thresholdAnn.y1 >= thresholds[i + 1]) ||
(i > 0 && thresholdAnn.y1 <= thresholds[i - 1])
) {
// Prevent reordering thresholds
thresholdAnn.y1 = thresholds[i];
} else {
// Update threshold from annotation position
thresholds[i] = thresholdAnn.y1;
paletteProvider.thresholds = thresholds;
transform.thresholds.set(i, thresholdAnn.y1);
}
});
sciChartSurface.annotations.add(thresholdAnn);
};
for (let i = 0; i < thresholds.length; i++) {
makeThresholdAnnotation(i);
}
sciChartSurface.annotations.add(
new NativeTextAnnotation({
xCoordinateMode: ECoordinateMode.Pixel,
yCoordinateMode: ECoordinateMode.Pixel,
x1: 20,
y1: 20,
horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
verticalAnchorPoint: EVerticalAnchorPoint.Top,
text: "Drag the horizontal lines to adjust the thresholds",
fontSize: 16,
textColor: appTheme.ForegroundColor,
})
);
sciChartSurface.chartModifiers.add(new ZoomPanModifier({ enableZoom: true }));
sciChartSurface.chartModifiers.add(new ZoomExtentsModifier());
sciChartSurface.chartModifiers.add(new MouseWheelZoomModifier());
sciChartSurface.zoomExtents();
return { sciChartSurface, wasmContext };
};
This example demonstrates how to split a line series into multiple segments based on defined threshold values using SciChart.js in JavaScript. The approach allows each segment to be individually colored by detecting where the data crosses specified thresholds and then applying interpolation to insert new points.
The core of this example is a custom RenderDataTransform that calculates intersections between data points and thresholds. This technique follows the guidelines outlined in the RenderDataTransforms API documentation. In addition, a custom PaletteProvider is implemented to assign different colors to each segment based on the current threshold level, as described in the PaletteProvider API documentation. Observable arrays provided by SciChart.js, particularly ObservableArrayBase, are used to detect changes in threshold values and trigger re-rendering of the chart. The interpolation logic responsible for calculating the exact intersection points leverages standard linear interpolation techniques.
The example showcases several advanced features:
FastLineRenderableSeries ensures the chart remains responsive even with additional points created through interpolation. Developers interested in optimizing rendering can refer to the Performance Tips & Tricks.Built with pure JavaScript, this example follows best integration practices for SciChart.js without relying on additional frameworks or builder APIs. Developers looking to integrate SciChart.js into standard web applications can benefit from the comprehensive guide available in Getting Started with SciChart JS. The modular structure and use of custom render transforms and palette providers make this example an excellent starting point for developing interactive, high-performance charts with dynamic data transformation capabilities.










