Dragabble Event Markers

Demonstrates how FastRectangleRenderableSeries and BoxAnnotation to make dragabble, labled, event markers, using SciChart.js High Performance JavaScript Charts

src/drawExample.ts
import {
    AUTO_COLOR,
    BoxAnnotation,
    CustomChartModifier2D,
    deleteSafe,
    EAxisAlignment,
    EColumnMode,
    EColumnYMode,
    ECoordinateMode,
    EHorizontalAnchorPoint,
    ENumericFormat,
    EValueName,
    EVerticalAnchorPoint,
    EXyDirection,
    FastLineRenderableSeries,
    FastRectangleRenderableSeries,
    formatNumber,
    IChartModifierBaseOptions,
    ModifierMouseArgs,
    MouseWheelZoomModifier,
    NumberRange,
    NumericAxis,
    RectangleDataLabelState,
    RectangleSeriesDataLabelProvider,
    SciChartSurface,
    SweepAnimation,
    TextAnnotation,
    XyDataSeries,
    XyxDataSeries,
    ZoomExtentsModifier,
    ZoomPanModifier,
} from "scichart";
import { RandomWalkGenerator } from "./RandomWalkGenerator";
import { appTheme } from "./appTheme";

const defaultHeight = 1;
class RectangleDragModifier extends CustomChartModifier2D {
    private series: FastRectangleRenderableSeries;
    private dataSeries: XyxDataSeries;
    private annotation: BoxAnnotation;
    private selectedIndex: number = -1;

    public constructor(series: FastRectangleRenderableSeries, options?: IChartModifierBaseOptions) {
        super(options);
        this.series = series;
        this.dataSeries = series.dataSeries as XyxDataSeries;
    }

    public override onAttach(): void {
        super.onAttach();
        // Create an annotation where only the selection box will be visible
        this.annotation = new BoxAnnotation({
            xAxisId: this.series.xAxisId,
            yAxisId: this.series.yAxisId,
            strokeThickness: 0,
            stroke: "transparent",
            selectionBoxStroke: "#88888844",
            opacity: 0,
            isEditable: true,
            resizeDirections: EXyDirection.XDirection,
            // dragPoints: [
            //     EDraggingGripPoint.Body,
            //     EDraggingGripPoint.x1y1,
            //     EDraggingGripPoint.x2y1,
            //     EDraggingGripPoint.x1y2,
            //     EDraggingGripPoint.x2y2,
            // ],
        });

        // Update the selected data point when the annotation is dragged
        this.annotation.dragDelta.subscribe((data) => {
            if (this.selectedIndex >= 0) {
                const newX = this.annotation.x1;
                const newY = Math.floor(this.annotation.y1 + defaultHeight);
                const newx1 = this.annotation.x2;

                // Do not allow close to be less than open as this breaks our custom hitTest
                this.dataSeries.updateXyz(
                    this.selectedIndex,
                    newX,
                    newY,
                    newx1,
                    this.dataSeries.getMetadataAt(this.selectedIndex)
                );
            }
        });

        // Manually set the selected status of the point using metadata.  This will drive the DataPointSelectionPaletteProvider
        this.annotation.selectedChanged.subscribe((data) => {
            this.dataSeries.getMetadataAt(this.selectedIndex).isSelected = data;
        });

        this.parentSurface.modifierAnnotations.add(this.annotation);
    }

    public override onDetach(): void {
        this.parentSurface.modifierAnnotations.remove(this.annotation);
        this.annotation = deleteSafe(this.annotation);
    }

    public override modifierMouseUp(args: ModifierMouseArgs): void {
        const point = args.mousePoint;
        const hitTestInfo = this.series.hitTestProvider.hitTest(point.x, point.y, 5);

        if (hitTestInfo.isHit) {
            if (this.selectedIndex >= 0 && this.selectedIndex !== hitTestInfo.dataSeriesIndex) {
                this.dataSeries.getMetadataAt(this.selectedIndex).isSelected = false;
            }

            const x1Values = this.dataSeries.getYValuesByName(EValueName.X1);

            const x1Value = x1Values.get(hitTestInfo.dataSeriesIndex);

            // Place the annotation over the selected box
            this.selectedIndex = hitTestInfo.dataSeriesIndex;
            this.annotation.x1 = hitTestInfo.xValue;
            this.annotation.x2 = x1Value;
            this.annotation.y1 = Math.round(hitTestInfo.yValue) - defaultHeight / 2;
            this.annotation.y2 = Math.round(hitTestInfo.yValue) + defaultHeight / 2;
            // Make the annotation selected.  Both these lines are required.
            this.annotation.isSelected = true;
            this.dataSeries.getMetadataAt(this.selectedIndex).isSelected = true;
            this.parentSurface.adornerLayer.selectedAnnotation = this.annotation;
        }
    }
}

export const drawExample = async (rootElement: string | HTMLDivElement) => {
    // Create a SciChartSurface
    const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    const POINTS = 1000;

    // Shared X axis
    const xAxis = new NumericAxis(wasmContext, { visibleRange: new NumberRange(0, POINTS) });
    sciChartSurface.xAxes.add(xAxis);

    // Separate Y axes for the data and events
    const yAxis = new NumericAxis(wasmContext, {
        axisAlignment: EAxisAlignment.Left,
        growBy: new NumberRange(0.05, 0.1),
    });
    const yEventAxis = new NumericAxis(wasmContext, {
        isVisible: false,
        visibleRange: new NumberRange(0, 12),
    });

    sciChartSurface.yAxes.add(yAxis, yEventAxis);

    // Create arrays of x, y values (just arrays of numbers)
    const { xValues, yValues } = new RandomWalkGenerator().getRandomWalkSeries(POINTS);

    // Create a line Series and add to the chart
    sciChartSurface.renderableSeries.add(
        new FastLineRenderableSeries(wasmContext, {
            dataSeries: new XyDataSeries(wasmContext, { xValues, yValues }),
            stroke: AUTO_COLOR,
            strokeThickness: 3,
            animation: new SweepAnimation({ duration: 500, fadeEffect: true }),
        })
    );

    // Our event bars will have variable width, but fixed height, so we use Xyx data
    const eventDataSeries = new XyxDataSeries(wasmContext);

    // Create event data.  Prevent overlap of events
    const rows = new Map<number, number>();
    const EVENTCOUNT = 30;
    let start = 0;
    for (let i = 0; i < EVENTCOUNT; i++) {
        start = start + Math.random() * ((2 * POINTS) / EVENTCOUNT);
        const end = start + 1 + Math.random() * ((2 * POINTS) / EVENTCOUNT);
        let row = 10;
        if (i === 0) {
            rows.set(row, end);
        } else {
            let last = rows.get(row);
            while (last > start) {
                row -= defaultHeight;
                last = rows.get(row) ?? 0;
            }
            rows.set(row, end);
        }

        eventDataSeries.append(start, row, end, { isSelected: false });
    }

    // Create a custom DataLabelProvider which uses the width of the bar as the value to display
    class BarWidthDataLabelProvider extends RectangleSeriesDataLabelProvider {
        public getText(state: RectangleDataLabelState): string {
            const usefinal = !this.updateTextInAnimation && state.parentSeries.isRunningAnimation;
            const yval = usefinal ? state.yValAfterAnimation() : state.yVal();
            if (isNaN(yval)) {
                return undefined;
            } else {
                const diff = Math.abs(state.x1Val() - state.xVal());
                if (this.engineeringPrefix) {
                    return formatNumber(diff, this.numericFormat, this.precision, this.engineeringPrefixProperty);
                } else {
                    return formatNumber(diff, this.numericFormat ?? ENumericFormat.Decimal, this.precision);
                }
            }
        }
    }

    const eventSeries = new FastRectangleRenderableSeries(wasmContext, {
        dataSeries: eventDataSeries,
        yAxisId: yEventAxis.id,
        columnXMode: EColumnMode.StartEnd,
        columnYMode: EColumnYMode.CenterHeight,
        defaultY1: defaultHeight,
        stroke: "ff0000cc",
        strokeThickness: 1,
        fill: "ff00004D",
        // opacity: 0.8,
        dataLabelProvider: new BarWidthDataLabelProvider({
            style: {
                fontSize: 12,
            },
            color: appTheme.ForegroundColor,
        }),
    });

    sciChartSurface.renderableSeries.add(eventSeries);

    // Configure modifiers to only affect the data Y axis
    sciChartSurface.chartModifiers.add(
        new ZoomExtentsModifier({ includedYAxisIds: [yAxis.id] }),
        new MouseWheelZoomModifier({ includedYAxisIds: [yAxis.id] }),
        new ZoomPanModifier({ includedYAxisIds: [yAxis.id] }),
        new RectangleDragModifier(eventSeries)
    );

    // Add instructions
    sciChartSurface.annotations.add(
        new TextAnnotation({
            x1: 0.01,
            y1: 0.03,
            xCoordinateMode: ECoordinateMode.Relative,
            yCoordinateMode: ECoordinateMode.Relative,
            horizontalAnchorPoint: EHorizontalAnchorPoint.Left,
            verticalAnchorPoint: EVerticalAnchorPoint.Top,
            text: "The boxes are rendered with a fast rectangle series and can be selected and dragged like an annotation.",
            textColor: appTheme.ForegroundColor + "77",
        })
    );

    xAxis.visibleRange = xAxis.getMaximumRange();

    return { wasmContext, sciChartSurface };
};

Draggable Event Markers on JavaScript Charts

Overview

This example, "Event Markers", demonstrates advanced charting features using SciChart.js with JavaScript. It showcases key techniques such as custom chart modifiers, data label customization, custom hit testing, axis range synchronization, interactive annotations, and performance optimizations.

Technical Implementation

The chart is created by instantiating a SciChartSurface with multiple axes and renderable series including FastLineRenderableSeries for a primary line chart and FastCandlestickRenderableSeries for event markers. A custom modifier, implemented by extending the CustomChartModifier2D API, enables selection and drag interactions on candlestick event markers. For more details on creating such custom modifiers, see the Custom Chart Modifier API.

Custom data labels are generated via an overridden DataLabelProvider, which dynamically calculates label positions and text by based on open and close values. Developers can refer to the DataLabel API documentation for similar implementations.

In addition, the example overrides the default hit testing behavior with custom logic that accounts for multiple overlapping series. This enables precise interaction with the candlestick markers and demonstrates techniques found in the RenderableSeries Hit-Test API demo.

The implementation also includes performance optimizations by utilizing FastLineRenderableSeries and applying a SweepAnimation for series startup, as described in the Series Startup Animations documentation. The getDataPointWidth() method is overridden to ensure fixed pixel width rendering for event markers, supporting custom rendering requirements.

Features and Capabilities

This example offers dynamic update capabilities through a drag-enabled custom chart modifier that updates the underlying OhlcDataSeries. Axis range synchronization is implemented whereby the axis.visibleRange of a hidden event axis is kept in sync with the main axis, ensuring consistent display during zoom and pan operations. Interactive annotations are integrated to let users select and drag markers, and the overall implementation follows best practices for resource management by returning a destructor function for proper disposal of the SciChartSurface. For guidance on resource cleanup, see the Memory Best Practices page.

Integration and Best Practices

The JavaScript integration is self-contained: the chart is created within an asynchronous initialization function that returns a cleanup function to properly dispose of the chart when necessary. This pattern ensures efficient memory management and aligns with best practices outlined in the SciChart documentation. Additionally, the combination of custom annotations and modifiers demonstrates how to build interactive and highly configurable chart components. Developers are encouraged to explore further customizations, such as advanced zooming and data streaming, by consulting the Editable Annotations documentation. Overall, the implementation serves as a solid foundation for integrating advanced SciChart.js features using JavaScript.