Realtime JavaScript Chart Performance Demo

Demonstrates appending millions of points to a line chart with SciChart.js, High Performance JavaScript Charts

# DataPoints: 0FPS: 00 
src/drawExample.ts
import { appTheme } from "./appTheme";
import { RandomWalkGenerator } from "./RandomWalkGenerator";

import {
    EAutoRange,
    EDragMode,
    ENumericFormat,
    FastLineRenderableSeries,
    MouseWheelZoomModifier,
    NumericAxis,
    RubberBandXyZoomModifier,
    SciChartSurface,
    XAxisDragModifier,
    XyDataSeries,
    YAxisDragModifier,
    ZoomExtentsModifier,
} from "scichart";

export const drawExample = async (rootElement: string | HTMLDivElement) => {
    // Define some constants
    const numberOfPointsPerTimerTick = 1000; // 1,000 points every timer tick
    const timerInterval = 10; // timer tick every 10 milliseconds
    const maxPoints = 1e6; // max points for a single series before the demo stops

    // Create a SciChartSurface
    // Note create() uses shared WebGL canvas, createSingle() uses one WebGL per chart
    // createSingle() = faster performance as doesn't require a copy-op, but limited by max-contexts in browser
    const { wasmContext, sciChartSurface } = await SciChartSurface.createSingle(rootElement, {
        theme: appTheme.SciChartJsTheme,
    });

    // Create an XAxis and YAxis with autoRange=Always
    const xAxis = new NumericAxis(wasmContext, { 
        autoRange: EAutoRange.Always,
        labelPrecision: 0,
        labelFormat: ENumericFormat.Engineering,
    });
    sciChartSurface.xAxes.add(xAxis);
    
    const yAxis = new NumericAxis(wasmContext, { autoRange: EAutoRange.Always });
    sciChartSurface.yAxes.add(yAxis);

    // Create some DataSeries
    const dataSeries: XyDataSeries[] = [
        new XyDataSeries(wasmContext, { containsNaN: false, isSorted: true }),
        new XyDataSeries(wasmContext, { containsNaN: false, isSorted: true }),
        new XyDataSeries(wasmContext, { containsNaN: false, isSorted: true }),
    ];

    const seriesColors = [appTheme.VividSkyBlue, appTheme.VividOrange, appTheme.VividPink];

    // Create some FastLineRenderableSeries bound to each dataSeries and add to the chart
    dataSeries.map((ds, index) => {
        sciChartSurface.renderableSeries.add(
            new FastLineRenderableSeries(wasmContext, {
                dataSeries: ds,
                strokeThickness: 2,
                stroke: seriesColors[index],
            })
        );
    });

    // Add some interactivity modifiers. These are only operational when the demo is paused
    // as interactivity conflicts with AutoRange.Always
    sciChartSurface.chartModifiers.add(
        new RubberBandXyZoomModifier(),
        new MouseWheelZoomModifier(),
        new XAxisDragModifier({ dragMode: EDragMode.Panning }),
        new YAxisDragModifier({ dragMode: EDragMode.Panning }),
        new ZoomExtentsModifier()
    );

    // This class generates some data for our example
    // It generates a random walk, which is a line which increases or decreases by a random value
    // each data-point
    const randomWalkGenerators = [1, 2, 3].map((_) => {
        return new RandomWalkGenerator(0);
    });

    let timerId: NodeJS.Timeout;

    // Function called when the user clicks stopUpdate button
    const stopUpdate = () => {
        clearTimeout(timerId);
        timerId = undefined;
        randomWalkGenerators.forEach((rw) => rw.reset());
        // Disable autoranging on X when the demo is paused. This allows zooming and panning
        xAxis.autoRange = EAutoRange.Once;
    };

    // Function called when the user clicks startUpdate button
    const startUpdate = () => {
        // // tslint:disable-next-line:no-debugger
        // debugger;
        if (timerId) {
            stopUpdate();
        }
        const updateFunc = () => {
            if (dataSeries[0].count() >= maxPoints) {
                stopUpdate();
                return;
            }

            randomWalkGenerators.forEach((randomWalk, index) => {
                // Get the next N random walk x,y values
                const { xValues, yValues } = randomWalk.getRandomWalkSeries(numberOfPointsPerTimerTick);

                // Append these to the dataSeries. This will cause the chart to redraw
                dataSeries[index].appendRange(xValues, yValues);
            });

            timerId = setTimeout(updateFunc, timerInterval);
        };

        // Enable autoranging on X when running the demo
        xAxis.autoRange = EAutoRange.Always;

        dataSeries.forEach((ds) => ds.clear());

        timerId = setTimeout(updateFunc, timerInterval);
    };

    type TRenderStats = { numberPoints: number; fps: number };
    type TOnRenderStatsChangeCallback = (stats: TRenderStats) => void;

    let statsCallback: TOnRenderStatsChangeCallback = () => {};
    const setStatsChangedCallback = (callback: TOnRenderStatsChangeCallback) => {
        statsCallback = callback;
    };

    let lastRendered = Date.now();
    sciChartSurface.renderedToDestination.subscribe(() => {
        const currentTime = Date.now();
        const timeDiffSeconds = new Date(currentTime - lastRendered).getTime() / 1000;
        lastRendered = currentTime;
        const fps = 1 / timeDiffSeconds;
        const renderStats = {
            numberPoints:
                sciChartSurface.renderableSeries.size() * sciChartSurface.renderableSeries.get(0).dataSeries.count(),
            fps,
        };

        statsCallback(renderStats);
    });

    return { wasmContext, sciChartSurface, controls: { startUpdate, stopUpdate, setStatsChangedCallback } };
};

Realtime Chart Performance Demo with JavaScript

Overview

This example, “JavaScript Chart Performance Demo”, demonstrates how to create a highly performant real-time chart using plain JavaScript and SciChart.js. The demo continuously appends large batches of data points to a line chart while measuring performance metrics such as frames per second (FPS), all powered by the efficient WebGL rendering capabilities of SciChart.js.

Technical Implementation

The implementation begins by asynchronously initializing a SciChartSurface using the dedicated WebGL canvas via the SciChartSurface.createSingle() method (see Adding Realtime Updates | JavaScript Chart Documentation). Two NumericAxis are created and configured with auto-ranging set to EAutoRange.Always, which is detailed in the Axis Ranging - AutoRange Documentation. Three XyDataSeries objects are instantiated and bound to FastLineRenderableSeries to efficiently render large ranges of data points. A setTimeout loop is used to drive the continuous, real-time data updates, with a RandomWalkGenerator appending 1,000 points every 10 milliseconds. Performance is measured by subscribing to the sciChartSurface.rendered event, which calculates metrics such as FPS and the total number of data points - techniques discussed in the Performance Tips & Tricks Guide.

Features and Capabilities

Real-Time Updates: The demo showcases live data streaming by continuously appending up to millions of data points. This demonstrates how efficiently DataSeries Realtime Updates can be implemented to handle high-frequency updates in JavaScript Charts with SciChart.

Axis Configuration: By using NumericAxis with an auto-range configuration, the chart automatically adjusts its view to new data without manual intervention. Developers interested in further details can review the Axis Ranging - AutoRange Documentation.

Asynchronous Initialization: The use of async/await ensures that the chart is set up efficiently and that resources are properly managed. This practice follows guidelines outlined in the Getting Started with SciChart JS documentation.

Performance Measurement: The rendered.subscribe event is leveraged to compute performance statistics like FPS, enabling developers to gain insights into rendering efficiency. For more on these techniques, see the Performance Tips & Tricks Guide.

Integration and Best Practices

Even though this example is implemented purely in JavaScript, the control patterns—such as starting/stopping real-time updates and cleaning up resources using a destructor function—are applicable to any framework. The chart controls provide methods to start and stop the update loop, and the SciChartSurface.delete() method is called to dispose of WebGL resources efficiently, aligning with the best practices detailed in the Memory Best Practices documentation. This example clearly illustrates how real-time chart updates, efficient data series handling, and performance measurement techniques can be combined in a JavaScript environment using SciChart.js.