JavaScript Gantt Chart Example

Creates a JavaScript Gantt Chart using SciChart.js, using the new FastRectangleSeries to draw horizontal bars, with rounded corners and data labels coming from metadata

Fullscreen

Edit

 Edit

Docs

drawExample.ts

index.html

vanilla.ts

theme.ts

Copy to clipboard
Minimise
Fullscreen
1import {
2    ZoomPanModifier,
3    ZoomExtentsModifier,
4    SciChartSurface,
5    ENumericFormat,
6    EAxisAlignment,
7    FastRectangleRenderableSeries,
8    XyxyDataSeries,
9    EColumnYMode,
10    EColumnMode,
11    EDataPointWidthMode,
12    NumberRange,
13    EHorizontalTextPosition,
14    EVerticalTextPosition,
15    SeriesInfo,
16    EXyDirection,
17    DateTimeNumericAxis,
18    CategoryAxis,
19    ELabelAlignment,
20    CursorModifier,
21    TCursorTooltipDataTemplate,
22} from "scichart";
23import { appTheme } from "../../../theme";
24
25const PROJECT_STAGES = [
26    "Project Planning",
27    "Requirements",
28    "System Design",
29    "Database Design",
30    "Front-end dev",
31    "Back-end dev",
32    "Integration",
33    "Unit Testing",
34    "System Testing",
35    "Deployment",
36];
37
38const PROJECT_TASKS = [
39    {
40        name: PROJECT_STAGES[0],
41        startDate: new Date(2025, 0, 1),
42        endDate: new Date(2025, 0, 15),
43        percentComplete: 100,
44    },
45    {
46        name: PROJECT_STAGES[1],
47        startDate: new Date(2025, 0, 10),
48        endDate: new Date(2025, 0, 25),
49        percentComplete: 100,
50    },
51    {
52        name: PROJECT_STAGES[2],
53        startDate: new Date(2025, 0, 20),
54        endDate: new Date(2025, 1, 15),
55        percentComplete: 90,
56    },
57    {
58        name: PROJECT_STAGES[3],
59        startDate: new Date(2025, 1, 5),
60        endDate: new Date(2025, 1, 20),
61        percentComplete: 85,
62    },
63    {
64        name: PROJECT_STAGES[4],
65        startDate: new Date(2025, 1, 15),
66        endDate: new Date(2025, 2, 25),
67        percentComplete: 70,
68    },
69    {
70        name: PROJECT_STAGES[5],
71        startDate: new Date(2025, 1, 15),
72        endDate: new Date(2025, 3, 5),
73        percentComplete: 60,
74    },
75    {
76        name: PROJECT_STAGES[6],
77        startDate: new Date(2025, 2, 25),
78        endDate: new Date(2025, 3, 15),
79        percentComplete: 30,
80    },
81    {
82        name: PROJECT_STAGES[7],
83        startDate: new Date(2025, 3, 1),
84        endDate: new Date(2025, 3, 20),
85        percentComplete: 20,
86    },
87    {
88        name: PROJECT_STAGES[8],
89        startDate: new Date(2025, 3, 15),
90        endDate: new Date(2025, 4, 5),
91        percentComplete: 0,
92    },
93    {
94        name: PROJECT_STAGES[9],
95        startDate: new Date(2025, 4, 1),
96        endDate: new Date(2025, 4, 15),
97        percentComplete: 0,
98    },
99];
100
101function prepareGanttData() {
102    // Prepare data for rect series
103    const xValues: number[] = []; // Start dates
104    const yValues: number[] = []; // Task positions (rows)
105    const x1Values: number[] = []; // End dates
106    const y1Values: number[] = []; // Task heights
107
108    // Task metadata for coloring and labels
109    const metaData: { name: string; percentComplete: number; isSelected: boolean; startDate: Date; endDate: Date }[] =
110        [];
111
112    // Convert Date objects to timestamps for rendering
113    PROJECT_TASKS.forEach((task, index) => {
114        const rowPosition = PROJECT_TASKS.length - index - 1; // Reverse order for display
115        const rowHeight = 0.8; // Height of each task bar
116
117        xValues.push(task.startDate.getTime() / 1000);
118        yValues.push(rowPosition);
119        x1Values.push(task.endDate.getTime() / 1000);
120        y1Values.push(rowPosition + rowHeight);
121
122        metaData.push({
123            name: task.name,
124            percentComplete: task.percentComplete,
125            isSelected: false,
126            startDate: task.startDate,
127            endDate: task.endDate,
128        });
129    });
130
131    return { xValues, yValues, x1Values, y1Values, metaData, taskCount: PROJECT_TASKS.length };
132}
133
134export const drawExample = async (rootElement: string | HTMLDivElement) => {
135    // Create a SciChartSurface
136    const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement, {
137        theme: appTheme.SciChartJsTheme,
138    });
139
140    const yAxis = new CategoryAxis(wasmContext, {
141        axisAlignment: EAxisAlignment.Left,
142        drawMajorBands: false,
143        drawLabels: true,
144        drawMinorGridLines: false,
145        drawMajorGridLines: false,
146        drawMinorTickLines: false,
147        drawMajorTickLines: false,
148        keepLabelsWithinAxis: false,
149        autoTicks: false,
150        majorDelta: 1,
151        growBy: new NumberRange(0.02, 0.02),
152        labels: PROJECT_STAGES.reverse(),
153        labelStyle: {
154            fontSize: 14,
155            fontWeight: "bold",
156            color: appTheme.MutedOrange,
157            alignment: ELabelAlignment.Right,
158            padding: { top: 0, right: 0, bottom: 40, left: 0 },
159        },
160    });
161
162    const xAxis = new DateTimeNumericAxis(wasmContext, {
163        axisAlignment: EAxisAlignment.Bottom,
164        drawMinorGridLines: false,
165        growBy: new NumberRange(0.02, 0.02),
166        // axisTitleStyle: {
167        //     fontSize: 14,
168        //     fontFamily: "Arial",
169        //     color: appTheme.MutedOrange,
170        //     // fontStyle: "italic",
171        // },
172        labelFormat: ENumericFormat.Date_DDMM,
173    });
174
175    sciChartSurface.xAxes.add(xAxis);
176    sciChartSurface.yAxes.add(yAxis);
177
178    sciChartSurface.yAxes.get(0).axisRenderer.hideOverlappingLabels = false;
179
180    const { xValues, yValues, x1Values, y1Values, metaData, taskCount } = prepareGanttData();
181
182    const rectangleGanttSeries = new FastRectangleRenderableSeries(wasmContext, {
183        dataSeries: new XyxyDataSeries(wasmContext, {
184            xValues,
185            yValues,
186            y1Values,
187            x1Values,
188            dataSeriesName: "Project Tasks",
189            metadata: metaData,
190        }),
191        columnXMode: EColumnMode.StartEnd,
192        columnYMode: EColumnYMode.TopBottom,
193        dataPointWidthMode: EDataPointWidthMode.Range,
194        stroke: appTheme.MutedRed,
195        strokeThickness: 2,
196        fill: appTheme.MutedBlue,
197        dataPointWidth: 0.9,
198        topCornerRadius: 4,
199        opacity: 0.5,
200        bottomCornerRadius: 4,
201        dataLabels: {
202            color: appTheme.ForegroundColor,
203            style: {
204                fontSize: 14,
205            },
206            numericFormat: ENumericFormat.Engineering,
207            verticalTextPosition: EVerticalTextPosition.Center,
208            horizontalTextPosition: EHorizontalTextPosition.Center,
209            metaDataSelector: (md) => {
210                const metadata = md as { name: string; percentComplete: number; isSelected: boolean };
211                return `${metadata.percentComplete.toString()} %`;
212            },
213        },
214    });
215
216    sciChartSurface.renderableSeries.add(rectangleGanttSeries);
217
218    const tooltipDataTemplate: TCursorTooltipDataTemplate = (seriesInfos: SeriesInfo[]) => {
219        const valuesWithLabels: string[] = [];
220
221        seriesInfos.forEach((si) => {
222            const xySI = si;
223            if (xySI.isWithinDataBounds) {
224                if (!isNaN(xySI.yValue) && xySI.isHit) {
225                    valuesWithLabels.push(
226                        `Start: ${new Date(
227                            (xySI.pointMetadata as { startDate: number }).startDate
228                        ).toLocaleDateString()}, End: ${new Date(
229                            (xySI.pointMetadata as { endDate: number }).endDate
230                        ).toLocaleDateString()}`
231                    );
232                }
233            }
234        });
235        return valuesWithLabels;
236    };
237
238    // Add interactivity modifiers
239    sciChartSurface.chartModifiers.add(
240        new ZoomPanModifier({
241            enableZoom: true,
242            xyDirection: EXyDirection.XDirection, // Only zoom horizontally
243        }),
244        new ZoomExtentsModifier(),
245        new CursorModifier({
246            showTooltip: true,
247            tooltipDataTemplate,
248            showXLine: false,
249            showYLine: false,
250            tooltipContainerBackground: appTheme.MutedRed + 55,
251        })
252    );
253
254    return {
255        sciChartSurface,
256        wasmContext,
257    };
258};
259

JavaScript Gantt Chart Example

Overview

This example demonstrates how to create a Gantt Chart using SciChart.js in vanilla JavaScript. The implementation visualizes project tasks with start/end dates and completion percentages using FastRectangleRenderableSeries with XyxyDataSeries for precise task positioning.

Technical Implementation

The chart uses a CategoryAxis for task names and DateTimeNumericAxis for timeline display. Tasks are rendered as rectangles with configurable corner radii, opacity, and data labels showing completion percentages. The implementation uses EColumnMode.StartEnd and EColumnYMode.TopBottom for precise rectangle positioning.

Features and Capabilities

Interactive features include horizontal zoom/pan via ZoomPanModifier and tooltips showing task dates through a custom TCursorTooltipDataTemplate. The chart efficiently handles task data conversion from Date objects to timestamps for rendering.

Integration and Best Practices

The example follows best practices for asynchronous chart initialization and includes proper cleanup. Developers can extend this by adding real-time updates or integrating with project management APIs.

javascript Chart Examples & Demos

See Also: Charts added in v4 (16 Demos)

JavaScript Histogram Chart | Javascript Charts | SciChart.js

JavaScript Histogram Chart

Create a JavaScript Histogram Chart with custom texture fills and patterns. Try the SciChart.js library for seamless integration today.

JavaScript Choropleth Map | Javascript Charts | SciChart.js Demo

JavaScript Choropleth Map Example

Create a JavaScript Choropleth map, a type of thematic map where areas are shaded or patterned in proportion to the value of a variable being represented.

JavaScript Multi-Layer Map | Javascript Charts | SciChart.js

JavaScript Multi-Layer Map Example

Create a JavaScript Multi-Layer Map Example, using FastTriangleRenderableSeries with GeoJSON data-points using a constrained delaunay triangulation algorithm.

JavaScript Animated Bar Chart | Javascript Charts | SciChart.js

JavaScript Animated Bar Chart Example

Bring annual comparison data to life with the JavaScript Animated Bar Chart example from SciChart. This demo showcases top 10 tennis players from 1990 to 2024.

JavaScript Vector Field Plot | Javascript Charts | SciChart.js

JavaScript Vector Field Plot

View the JavaScript Vector Field Plot example from SciChart, including dynamic vector generation, gradient-colored segments, and interactive zoom/pan. Try demo.

JavaScript Waterfall Chart | Bridge Chart | SciChart.js

JavaScript Waterfall Chart | Bridge Chart

Build a JavaScript Waterfall Chart with dynamic coloring, multi-line data labels and responsive design. Try SciChart.js for seamless integration today.

JavaScript Box Plot Chart | Javascript Charts | SciChart.js Demo

JavaScript Box Plot Chart

Try the JavaScript Box-Plot Chart examples with developer-friendly chart lifecycle management, dynamic sub-surface positioning, and custom styling.

JavaScript Triangle Series | Triangle Mesh Chart | SciChart

JavaScript Triangle Series | Triangle Mesh Chart

Create JavaScript Triangle Meshes with the Triangle Series from SciChart. This demo supports strip mode, list mode and the drawing of polygons. View the example.

JavaScript Treemap Chart | Javascript Charts | SciChart.js Demo

JavaScript Treemap Chart

Create a JavaScript Treemap Chart to define rectangle positions based on total value. Use SciChart FastRectangleRenderableSeries and d3-hierarchy.js layouts.

NEW!
JavaScript Map Chart with Heatmap overlay | SciChart.js

JavaScript Map Chart with Heatmap overlay

Design a highly dynamic JavaScript Map Chart with Heatmap overlay with SciChart's feature-rich JavaScript Chart Library. Get your free demo today.

Realtime Audio Analyzer Bars Demo | SciChart.js Demo

Realtime Audio Analyzer Bars Demo

Demonstrating the capability of SciChart.js to create a JavaScript Audio Analyzer Bars and visualize the Fourier-Transform of an audio waveform in realtime.

JavaScript Linear Gauges | Javascript Charts | SciChart.js Demo

JavaScript Linear Gauges Example

View the JavaScript Linear Gauge Chart example to combine rectangles & annotations. Create a linear gauge dashboard with animated indicators and custom scales.

NEW!
JavaScript Order of Rendering | Javascript Charts | SciChart.js

JavaScript Order of Rendering Example

The JavaScript Order of Rendering example gives you full control of the draw order of series and annotations for charts. Try SciChart's advanced customizations.

Responsive HTML Annotations | Javascript Charts | SciChart.js

JavaScript Responsive HTML Annotations Example

Build Responsive JavaScript HTML Annotations with SciChart. Use the advanced CSS container queries for responsive text layout and custom design. View demo now.

HTML Annotations and Custom in-chart Controls | SciChart

HTML Annotations and Custom in-chart Controls Example

JavaScript HTML Chart Control example demonstrates advanced HTML annotation integration and how to render HTML components within charts. Try the SciChart demo.

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.

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