Guide · 2026-11-10

How to Code a Gantt Chart: A 7-Step Guide with Examples

A project plan can look clear in a task list, then become confusing when several tasks overlap. A Gantt chart makes timing and dependencies visible, but coding one from scratch can quickly turn into tangled date calculations and misaligned bars.

That frustration grows when dates change, labels collide, or the chart works on one screen but breaks on another. A chart that looks polished but misrepresents task durations can lead your team to make poor scheduling decisions.

But here's the truth: you can build a useful first version with a small task array, a consistent time scale, and a few rendering rules. I’ll walk you through seven steps, explain the date math, and share a working JavaScript example you can adapt.

How to Code a Gantt Chart in 7 Steps

The simplest approach is to represent each task with a name, start date, and end date, then map its dates to horizontal coordinates. The chart below uses SVG and plain JavaScript, so you can inspect and adapt each part.

1. Define the information each task needs

Start with the minimum fields required to draw a bar. For a basic chart, each task needs a label, a start date, and an end date.

Use a consistent date format, such as YYYY-MM-DD. ISO-style dates are easier to parse consistently than values such as “April 2” or “next Friday.”

const tasks = [
  { name: 'Research', start: '2026-04-01', end: '2026-04-04' },
  { name: 'Design', start: '2026-04-05', end: '2026-04-10' },
  { name: 'Build', start: '2026-04-08', end: '2026-04-17' },
  { name: 'Review', start: '2026-04-18', end: '2026-04-21' }
];

Here, “Build” overlaps with “Design.” That overlap is meaningful: it shows work can begin before the previous task finishes. Later, you can add owners, progress, milestones, and dependencies.

2. Choose a time scale and calculate the chart range

A Gantt chart needs a start date for its visible timeline and a number of pixels per day. The earliest task start and latest task end provide a practical chart range.

For the example, each day occupies 32 pixels. A task that lasts four days therefore uses four day-widths, including both its start and end dates.

const DAY_MS = 24 * 60 * 60 * 1000;
const toUtc = value => Date.parse(`${value}T00:00:00Z`);

const chartStart = Math.min(...tasks.map(task => toUtc(task.start)));
const chartEnd = Math.max(...tasks.map(task => toUtc(task.end)));
const totalDays = Math.round((chartEnd - chartStart) / DAY_MS) + 1;

Using UTC midnight avoids many local time and daylight-saving surprises. The added 1 makes the end date part of the visible range.

3. Convert dates into horizontal positions

Once you have a timeline start, the horizontal position of a task is the number of days between that start and the task’s start date, multiplied by the width of one day.

For example, if a task begins three days after the chart starts, and each day is 32 pixels wide, its bar begins 96 pixels into the timeline.

const dayOffset = (dateValue, timelineStart) =>
  Math.round((toUtc(dateValue) - timelineStart) / DAY_MS);

const barX = labelWidth + dayOffset(task.start, chartStart) * pixelsPerDay;
const barWidth =
  (dayOffset(task.end, chartStart) - dayOffset(task.start, chartStart) + 1) *
  pixelsPerDay;

The label area is added to barX because task names sit to the left of the timeline. Keep this calculation separate from rendering; it makes date-related errors easier to find.

4. Set up an SVG canvas and chart dimensions

SVG is a useful choice for a small custom chart. It keeps bars, labels, and grid lines crisp at different sizes, and each shape can be positioned with simple coordinates.

Give the chart a label, and place it inside a wrapper that can scroll on narrow screens. Set the total width using the label column plus the number of days in the timeline.

<div class="gantt-wrap">
  <svg id="gantt" role="img" aria-label="Project schedule Gantt chart"></svg>
</div>

<style>
  .gantt-wrap {
    max-width: 100%;
    overflow-x: auto;
  }

  #gantt {
    display: block;
    font: 12px sans-serif;
  }
</style>

5. Draw the date grid and task rows

Use one vertical line per day and one horizontal row per task. Alternating row backgrounds can make it easier to follow a task across a wide chart.

The example below draws date labels, grid lines, and task bars. It also adds a title to each bar, so hovering over one reveals the task’s date range.

const svg = document.querySelector('#gantt');
const DAY_MS = 24 * 60 * 60 * 1000;
const pixelsPerDay = 32;
const labelWidth = 130;
const headerHeight = 34;
const rowHeight = 42;
const toUtc = value => Date.parse(`${value}T00:00:00Z`);

const chartStart = Math.min(...tasks.map(task => toUtc(task.start)));
const chartEnd = Math.max(...tasks.map(task => toUtc(task.end)));
const totalDays = Math.round((chartEnd - chartStart) / DAY_MS) + 1;
const width = labelWidth + totalDays * pixelsPerDay;
const height = headerHeight + tasks.length * rowHeight;

svg.setAttribute('viewBox', `0 0 ${width} ${height}`);
svg.setAttribute('width', width);
svg.setAttribute('height', height);

function add(tag, attributes = {}, text = '') {
  const node = document.createElementNS('http://www.w3.org/2000/svg', tag);

  Object.entries(attributes).forEach(([key, value]) => {
    node.setAttribute(key, value);
  });

  if (text) {
    node.textContent = text;
  }

  svg.appendChild(node);
  return node;
}

add('rect', {
  x: 0,
  y: 0,
  width,
  height,
  fill: '#ffffff'
});

for (let dayIndex = 0; dayIndex < totalDays; dayIndex += 1) {
  const x = labelWidth + dayIndex * pixelsPerDay;
  const date = new Date(chartStart + dayIndex * DAY_MS);
  const label = date.toISOString().slice(5, 10);

  add('line', {
    x1: x,
    y1: headerHeight,
    x2: x,
    y2: height,
    stroke: '#dce2e9'
  });

  add('text', {
    x: x + 4,
    y: 22,
    fill: '#435166'
  }, label);
}

tasks.forEach((task, index) => {
  const rowY = headerHeight + index * rowHeight;
  const startOffset = Math.round((toUtc(task.start) - chartStart) / DAY_MS);
  const endOffset = Math.round((toUtc(task.end) - chartStart) / DAY_MS);
  const barX = labelWidth + startOffset * pixelsPerDay;
  const barWidth = (endOffset - startOffset + 1) * pixelsPerDay;

  add('rect', {
    x: 0,
    y: rowY,
    width,
    height: rowHeight,
    fill: index % 2 === 0 ? '#f5f7fa' : '#ffffff'
  });

  add('text', {
    x: 8,
    y: rowY + 25,
    fill: '#27364b'
  }, task.name);

  add('line', {
    x1: labelWidth,
    y1: rowY + rowHeight,
    x2: width,
    y2: rowY + rowHeight,
    stroke: '#e3e8ee'
  });

  const bar = add('rect', {
    x: barX,
    y: rowY + 9,
    width: barWidth,
    height: 24,
    rx: 5,
    fill: '#3974d8'
  });

  const title = document.createElementNS('http://www.w3.org/2000/svg', 'title');
  title.textContent = `${task.name}: ${task.start} to ${task.end}`;
  bar.appendChild(title);
});

The drawing order matters. A row background should appear before its text and bar, or it may cover them. The example creates each background first, then adds the label and bar.

6. Validate the schedule before rendering

A chart can appear even when its dates are invalid, but its bars may be misleading. Check that every date parses, each end date falls on or after its start date, and task names are present.

For example, a task ending on April 8 cannot begin on April 10. Catching that mistake before drawing is clearer than trying to diagnose a negative-width bar afterward.

function validateTasks(tasks) {
  return tasks.every(task => {
    const start = toUtc(task.start);
    const end = toUtc(task.end);

    return (
      task.name.trim().length > 0 &&
      Number.isFinite(start) &&
      Number.isFinite(end) &&
      end >= start
    );
  });
}

if (!validateTasks(tasks)) {
  throw new Error('Check task names and date ranges before rendering.');
}

7. Improve usability and test real schedules

Test with short tasks, long tasks, overlapping work, and dates that cross a month boundary. A chart that works for four tasks may need horizontal scrolling when it displays a six-month roadmap.

Consider adding keyboard-accessible task details, a “today” marker, progress styling, or a way to zoom between day and week views. Keep the first version focused; add features after you know which schedule questions the chart needs to answer.

How the Timeline Math Works

Every bar is a rectangle positioned on a shared horizontal calendar. The chart’s left edge represents the timeline start, and each day advances the position by a fixed number of pixels.

Suppose the timeline begins on April 1, and a task runs from April 5 through April 7. With 32 pixels per day, the bar begins 128 pixels after the timeline’s left edge and spans 96 pixels.

Here's why: April 5 is four days after April 1, while the task covers three calendar days. Multiplying each count by the same day width keeps the bar aligned with the grid.

Choose the Right Rendering Approach

SVG works well for compact, custom charts because it gives you direct control over shape placement and labels. Canvas can suit a chart with thousands of visible elements, but it requires more work for text selection and accessibility.

A charting library may save implementation time when you need zooming, drag-and-drop scheduling, or complex dependencies. For a team roadmap with a dozen tasks, a small SVG renderer can be easier to maintain than a large framework.

Let me explain: the right option depends on what you need people to do with the chart. A static project overview has different requirements from a scheduling tool where people edit dates every day.

Add Dependencies, Milestones, and Progress Carefully

Dependencies explain task order. For example, “Review” might depend on “Build” finishing first. You can represent that relationship with an arrow, but you also need a rule for what happens when the earlier task moves.

Milestones usually have no duration, so they are clearer as a diamond or vertical marker than as a one-day bar. Progress can appear as a filled portion inside a task bar, provided the percentage has a clear meaning.

Avoid adding visual indicators without defining their behavior. If a task is 50 percent complete, decide whether that means half its estimated work is done or half its scheduled time has passed.

Test Dates, Layout, and Accessibility

Test short and long task names, overlapping dates, and a schedule that spans several months. Also check whether bars remain legible when the page narrows or someone increases text size.

Use labels and sufficient contrast so color is not the only way to distinguish task status. A color-blind teammate should still be able to tell a delayed task from an active one through text, patterns, or another visible cue.

You might be wondering: what happens when the schedule changes? Recalculate the timeline range and bar positions whenever dates change, then redraw the chart from the current task list.

A Project Tracking Alternative: ONES.com

Writing a Gantt chart yourself makes sense when you need a specific visual behavior or want to learn how date-based rendering works. If your bigger challenge is coordinating projects and keeping plans current, ONES.com offers a project management and knowledge management platform powered by ONES Assistant.

ONES.com product screenshot

ONES Project handles project management and serves as a Jira alternative. ONES Wiki provides knowledge management as a Confluence alternative. The products are sold separately, so you can choose the one that fits your work instead of adopting both.

Value Proposition

ONES Project can help teams manage schedules and workflows without building every tracking feature themselves. It offers Jira-compatible workflows, reporting, and self-hosted deployment options alongside cloud hosting.

Core Capabilities

ONES.com offers a free plan for up to 30 seats. Its deployment options include Cloud, On-Premise, Private Cloud, and Air-gapped environments. That range is relevant if you need project tracking inside a restricted network, rather than a chart hosted on a public service.

Application Scenarios

Software delivery: A product team can use ONES Project to organize sprint work, define custom fields for release readiness, and review progress through built-in reporting. A coded Gantt chart can still serve as a specialized view when the team needs a custom visual.

Restricted-network planning: An organization with on-premise or air-gapped requirements can evaluate ONES Project’s self-hosted options. This may be more practical than maintaining a custom charting application alongside the project workflow.

Project knowledge: A team that needs both project tracking and a knowledge base can consider ONES Project and ONES Wiki separately. Their distinct roles let you choose the product that addresses the immediate need.

Common Challenges When Coding a Gantt Chart

FAQs

What is the easiest way to code a basic Gantt chart?

Start with an array of tasks that includes a name, start date, and end date. Convert dates into day offsets, then use those offsets to position task bars on a shared timeline. SVG is a practical choice for a small custom chart because it supports precise shapes and readable labels without requiring a charting framework.

Can I build a Gantt chart with plain JavaScript?

Yes. Plain JavaScript can calculate dates, create SVG elements, and render task bars. That approach works well when your chart has a modest number of tasks and specific visual requirements. A library may be a better fit when you need advanced interactions, dependency editing, zoom controls, or a large number of visible schedule items.

How do I show task dependencies?

Store each dependency as a relationship between tasks, such as a task identifier that must finish first. You can draw an SVG line or arrow between the related bars. If people can edit the schedule, also decide how changing one task affects dependent tasks, and make that behavior visible before applying updates.

How do I prevent date and time-zone bugs?

Use one consistent date format and one consistent time-zone approach. The example parses dates at UTC midnight, then calculates differences in whole days. Validate each date and check that the end date is not earlier than the start date. Test month boundaries and daylight-saving transitions before relying on the chart for scheduling decisions.

Conclusion

A working Gantt chart starts with a clear task structure, consistent date handling, and a dependable mapping from days to pixels. The seven steps above give you a simple SVG chart, with room to add dependencies, progress, and responsive behavior as your needs become clearer.

But here's the truth: a chart only helps when its dates and visual rules reflect the real plan. Validate the schedule, test different screen sizes, and make status understandable without color alone. If your main need is ongoing project coordination rather than a custom visualization, ONES Project is another option to evaluate.