快速开始

Timeline Canvas 是一个高性能、插件化的 Canvas 时间轴组件,采用秒制相对时间(所有时间从起点开始累计秒数)。

基础用法

下面是最小可运行示例:创建 canvas → 初始化 Timeline → 加载数据 →(可选)加载插件。

1. 安装

npm install timeline-canvas
# 或者
yarn add timeline-canvas
# 或者
pnpm add timeline-canvas

2. 创建画布

<canvas id="timelineCanvas" style="width: 100%; height: 600px;"></canvas>

3. 初始化时间轴(秒制时间系统)

import { Timeline } from "timeline-canvas";

const timeline = new Timeline("timelineCanvas", {
  startTime: 0,
  endTime: 3600,
  canvasHeight: 600,
  trackHeight: 46,
  trackMargin: 10,
});

4. 加载数据(秒制时间)

timeline.loadData({
  tracks: [
    {
      events: [
        {
          startTime: 0,
          endTime: 900,
          title: "前端开发",
          description: "完成用户界面开发",
        },
      ],
    },
    {
      events: [
        {
          startTime: 1800,
          endTime: 2700,
          title: "设计评审",
          description: "UI/UX 设计评审会议",
        },
      ],
    },
  ],
});

5. 添加插件(可选)

usePlugin() 返回 Promise<boolean>,用于确认插件是否加载成功。

import {
  ContextMenuPlugin,
  LightThemePlugin,
  PerformanceOverlayPlugin,
} from "timeline-canvas/plugins";

timeline.config.enableContextMenu = true;
timeline.config.contextMenuItems = [
  { type: "detail", name: "查看详情" },
  { type: "delete", name: "删除" },
];

await timeline.usePlugin(LightThemePlugin);
await timeline.usePlugin(PerformanceOverlayPlugin);
await timeline.usePlugin(ContextMenuPlugin());

进一步阅读

架构概览(可选)

在 VS Code 中使用 MCP(可选)

如果你使用 VS Code + Copilot Chat,并希望让 AI 以“工具调用”的方式协助生成插件骨架、做校验或触发 allowlist 脚本,请参考:

完整示例(与 Demo 一致的秒制用法)

<!DOCTYPE html>
<html>
<head>
  <title>Timeline Canvas 示例</title>
  <style>
    #timeline-container {
      width: 100%;
      height: 600px;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>
  <canvas id="timelineCanvas"></canvas>

  <script type="module">
    import { Timeline } from 'timeline-canvas';
    import {
      ContextMenuPlugin,
      LightThemePlugin,
      PerformanceOverlayPlugin,
    } from 'timeline-canvas/plugins';

    const timeline = new Timeline('timelineCanvas', {
      startTime: 0,
      endTime: 3600,
      enableContextMenu: true,
      contextMenuItems: [
        { type: 'detail', name: '查看详情' },
        { type: 'delete', name: '删除' },
      ],
    });

    // 加载示例数据(秒制)
    timeline.loadData({
      tracks: [{ events: [{ startTime: 0, endTime: 900, title: '第一阶段开发' }] }]
    });

    // 添加插件
    await timeline.usePlugin(LightThemePlugin);
    await timeline.usePlugin(PerformanceOverlayPlugin);
    await timeline.usePlugin(ContextMenuPlugin());

    // 动态切换主题
    // 切换到暗色主题
    setTimeout(() => void timeline.setTheme('dark'), 1000);
  </script>
</body>
</html>