Zoom and Pan a Realtime JavaScript Chart

Zoom the real-time chart below by dragging on the surface. Right click and drag to pan. Then double-click to reset zoom and start automatically scrolling again.

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.html

vanilla.ts

theme.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    EExecuteOn,
3    EllipsePointMarker,
4    EZoomState,
5    FastLineRenderableSeries,
6    NumberRange,
7    NumericAxis,
8    RubberBandXyZoomModifier,
9    SciChartSurface,
10    XyDataSeries,
11    XyScatterRenderableSeries,
12    ZoomExtentsModifier,
13    ZoomPanModifier,
14} from "scichart";
15
16import { appTheme } from "../../../theme";
17
18export const drawExample = async (rootElement: string | HTMLDivElement) => {
19    // Create the SciChartSurface in the div 'scichart-root'
20    // The SciChartSurface, and webassembly context 'wasmContext' are paired. This wasmContext
21    // instance must be passed to other types that exist on the same surface.
22    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
23        theme: appTheme.SciChartJsTheme,
24    });
25
26    // Create an X,Y Axis and add to the chart
27    const xAxis = new NumericAxis(wasmContext, { labelPrecision: 0 });
28    const yAxis = new NumericAxis(wasmContext);
29
30    sciChartSurface.xAxes.add(xAxis);
31    sciChartSurface.yAxes.add(yAxis);
32
33    // Create a Scatter series, and Line series and add to chart
34    const scatterSeries = new XyScatterRenderableSeries(wasmContext, {
35        pointMarker: new EllipsePointMarker(wasmContext, { width: 7, height: 7, fill: "White", stroke: "SteelBlue" }),
36    });
37    const lineSeries = new FastLineRenderableSeries(wasmContext, { stroke: "#4083B7", strokeThickness: 2 });
38    sciChartSurface.renderableSeries.add(lineSeries, scatterSeries);
39
40    const initialDataPointsCount = 1000;
41
42    // if a required size of data series is known or it is expected to grow,
43    // setting a capacity value may give some efficiency boost
44    const initialCapacity = 2000;
45
46    // Create and populate some XyDataSeries with static data
47    // Note: you can pass xValues, yValues arrays to constructors, and you can use appendRange for bigger datasets
48    const scatterData = new XyDataSeries(wasmContext, { dataSeriesName: "Cos(x)", capacity: initialCapacity });
49    const lineData = new XyDataSeries(wasmContext, { dataSeriesName: "Sin(x)", capacity: initialCapacity });
50
51    for (let i = 0; i < initialDataPointsCount; i++) {
52        lineData.append(i, Math.sin(i * 0.05));
53        scatterData.append(i, Math.cos(i * 0.05));
54    }
55
56    // Assign these dataseries to the line/scatter renderableseries
57    scatterSeries.dataSeries = scatterData;
58    lineSeries.dataSeries = lineData;
59
60    //  We disable ZoomExtends animation
61    sciChartSurface.chartModifiers.add(new ZoomExtentsModifier({ isAnimated: false }));
62    // Realtime zooming example
63    sciChartSurface.chartModifiers.add(new RubberBandXyZoomModifier());
64    // Realtime panning example
65    sciChartSurface.chartModifiers.add(
66        new ZoomPanModifier({ executeCondition: { button: EExecuteOn.MouseRightButton } })
67    );
68
69    // Part 2: Appending data in realtime
70    //
71    let timerId: NodeJS.Timeout;
72
73    const updateDataFunc = () => {
74        // Append another data-point to the chart. We use dataSeries.count()
75        // to determine the current length before appending
76        // NOTE: sometimes appending data points in bulk with appendRange can be more efficient
77        const i = lineData.count();
78        lineData.append(i, Math.sin(i * 0.05));
79        scatterData.append(i, Math.cos(i * 0.05));
80
81        // If the zoomState is not UserZooming, then we are viewing the extents of the data
82        // In this case, we want to scroll the chart by setting visibleRange = NumberRange(i-1000, i)
83        if (sciChartSurface.zoomState !== EZoomState.UserZooming) {
84            xAxis.visibleRange = new NumberRange(i - 1000, i);
85        }
86    };
87
88    const startUpdate = () => {
89        // Repeat at 60Hz
90        timerId = setInterval(updateDataFunc, 16);
91        // Warning, this will repeat forever, it's not best practice!
92    };
93
94    const stopUpdate = () => {
95        clearTimeout(timerId);
96    };
97
98    return { sciChartSurface, controls: { startUpdate, stopUpdate } };
99};
100

Realtime Chart Zoom Pan - JavaScript

Overview

This example demonstrates a real-time updating chart built with SciChart.js using JavaScript. The primary focus is on rendering a dynamic X-Y chart that displays updating sine and cosine data in real time. By leveraging a WebAssembly context via the SciChartSurface API, the example achieves high performance in rendering and interactive data visualization.

Technical Implementation

The chart is initialized by calling the asynchronous method SciChartSurface.create(), which creates both the SciChartSurface and its associated WebAssembly context. Axes are created as instances of NumericAxis and added to the chart. Two types of renderable series are used: a FastLineRenderableSeries for the sine data and an XyScatterRenderableSeries for the cosine data. Data is stored in XyDataSeries objects that are preallocated with a specified capacity; this preallocation is a key performance optimization described in the Performance Tips & Tricks section of the documentation.

Real-time updates are implemented using JavaScript’s setInterval to append new data points at a 60Hz frequency. The update function uses the dataSeries.append method to add points, and if the user is not interacting by zooming (as determined via the zoomState property), the visibleRange of the xAxis is updated to auto-scroll the view. For more details on real-time data updates, see the DataSeries Realtime Updates documentation.

Interactive behavior is enabled through the use of chart modifiers. The example adds a RubberBandXyZoomModifier to allow users to perform intuitive zooming and a ZoomPanModifier configured to execute on the mouse right button for panning. Additionally, a ZoomExtentsModifier is added with animations disabled for a smoother real-time experience; refer to the ZoomExtentsModifier documentation for further information.

Features and Capabilities

Real-time Updates: The example continuously appends sine and cosine data points using a timer, resulting in a live updating chart that auto-scrolls when not being manually zoomed.

Interactivity: Users can interact with the chart via rubber band zoom and right-button pan, making full use of the interactive modifier system built into SciChart.js.

Performance Optimizations: Preallocating capacity in the XyDataSeries improves update performance and reduces memory reallocations. The use of a WebAssembly context ensures that rendering remains fast even under high update rates.

Integration and Best Practices

While this example is implemented in JavaScript, similar approaches are used across frameworks like React and Angular, where the core charting engine remains the same. Best practices such as proper initialization using SciChartSurface.create(), efficient real-time data handling with dataSeries.append, and effective resource cleanup via a destructor function (sciChartSurface.delete()) are emphasized. Developers are encouraged to explore additional practices, such as managing the zoom state for auto-scrolling, detailed in the Tutorial 05 - Zoom and Pan with Realtime Updates documentation.

This example serves as a comprehensive guide for creating fast, interactive, and real-time charting applications with SciChart.js using JavaScript.

javascript Chart Examples & Demos

See Also: Zoom and Pan a Chart (9 Demos)

JavaScript Chart with Multiple X Axes | SciChart.js Demo

JavaScript Chart with Multiple X Axes

Demonstrates Multiple X & Y Axis on a JavaScript Chart using SciChart.js. SciChart supports unlimited left, right, top, bottom X, Y axis with configurable alignment and individual zooming, panning

JavaScript Chart with Secondary Y Axes | SciChart.js Demo

JavaScript Chart with Secondary Y Axes

Demonstrates Secondary Y Axis on a JavaScript Chart using SciChart.js. SciChart supports unlimited, multiple left, right, top, bottom X, Y axis with configurable alignment and individual zooming, panning

Drag JavaScript Chart Axis to Scale or Pan | SciChart.js

Drag JavaScript Chart Axis to Scale or Pan

Demonstrates how to Zoom, Scale or Pan individual Axis on a JavaScript Chart with SciChart.js AxisDragModifiers

Zoom and Pan with JavaScript Chart multiple Modifiers

Zoom and Pan with JavaScript Chart multiple Modifiers

Demonstrates how to use multiple Zoom and Pan Modifiers on a JavaScript Chart with SciChart.js

Zoom and Pan with Overview Chart | Javascript Charts | SciChart.js

Zoom and Pan with Overview Chart

Demonstrates how to zoom and pan with an Overview Chart

Virtualized JavaScript Charts: Load Data on Zoom/Pan

Virtualized JavaScript Charts: Load Data on Zoom/Pan

shows how to load data on zoom/pan and how to create an overview chart for this case.

JavaScript Polar Modifiers | Polar Interactivity Modifiers

JavaScript Polar Modifiers | Polar Interactivity Modifiers Demo

Explore SciChart's Polar Interactivity Modifiers including zooming, panning, and cursor tracking. Try the demo to trial the Polar Chart Behavior Modifiers.

NEW!
High Precision Date Axis | Javascript Charts | SciChart.js Demo

High Precision Date Axis

Demonstrates 64-bit precision Date Axis in SciChart.js handling Nanoseconds to Billions of Years

NEW!
JavaScript Overview for SubCharts with Range Selection

JavaScript Overview for SubCharts with Range Selection

Demonstrates how to create multiple synchronized subcharts with an overview range selector using SciChart.js and SubSurfaces

SciChart Ltd, 16 Beaufort Court, Admirals Way, Docklands, London, E14 9XL.