首页 文档 下载安装 GitHub
EN

Figcraft 文档

代码驱动的专业 SVG 图表库,适用于 TypeScript / Node.js。

安装

npm install figcraft

需要 Node.js 18+。该库无浏览器依赖,完全在 Node.js 中运行。

基本用法

创建 diagram.ts 文件,然后用 npx tsx diagram.ts 运行:

import { Figure } from 'figcraft'

const fig = new Figure(800, 400, { bg: '#fff' })

const a = fig.rect('输入', {
  pos: [50, 100], size: [120, 50],
  fill: '#e3f2fd', radius: 6
})

const b = fig.rect('输出', {
  pos: [250, 100], size: [120, 50],
  fill: '#c8e6c9', radius: 6
})

fig.arrow(a, b, { head: 'stealth', label: 'data' })

await fig.export('diagram.svg', { fit: true, margin: 20 })

Figure 构造函数

new Figure(width?: number, height?: number, options?: FigureOptions)
参数类型默认值说明
widthnumber800画布宽度(像素)
heightnumber400画布高度(像素)
optionsFigureOptions{}见下方 FigureOptions

FigureOptions

属性类型默认值说明
bgstring透明背景颜色
fontFamilystring系统字体默认字体族
mathFontstring'Times New Roman'$数学公式$ 使用的字体
codeFontstring'Menlo'`代码` 使用的字体
fontsstring[][]注册本地字体名称
autoAlignbooleantrue自动对齐同行元素
antiOverlapbooleantrue自动防止箭头标签重叠
alignTolerancenumber20行检测 Y 轴容差(像素)

字体注册

fig.font(name: string, source?: string)

注册字体以在图表中使用:

// 本地系统字体
fig.font('PingFang SC')

// Google Fonts
fig.font('Inter', 'google')

// 自定义 URL
fig.font('MyFont', 'https://example.com/font.woff2')

元素类型概览

Figcraft 提供 10 种元素类型,全部通过 fig.<type>(label, config?) 创建。

类型方法说明关键配置
rectfig.rect()圆角矩形radius
circlefig.circle()圆形r(默认: 30)
textfig.text()文本标签(支持 Markdown)fontSize, bold
imagefig.image()嵌入图片src, size
diamondfig.diamond()菱形决策节点size
trapezoidfig.trapezoid()梯形(池化/缩减)topRatio (0-1)
cylinderfig.cylinder()3D 圆柱体(数据库/CNN)depth(默认: 0.15)
cuboidfig.cuboid()3D 长方体(张量)depth(默认: 15px)
spherefig.sphere()3D 球体r(默认: 30)
stackfig.stack()多层堆叠count(默认: 3), stackOffset

2D 图形

矩形 (Rect)

const box = fig.rect('标签', {
  pos: [50, 50], size: [120, 60],
  fill: '#e3f2fd', radius: 8,
  stroke: { color: '#1565c0', width: 2 }
})
矩形示例

圆形 (Circle)

const node = fig.circle('节点', {
  pos: [200, 100], r: 35,
  fill: '#fff3e0', color: '#e65100'
})
圆形示例

菱形 (Diamond)

const decision = fig.diamond('是否?', {
  pos: [100, 100], size: [80, 60],
  fill: '#fce4ec'
})
菱形示例

梯形 (Trapezoid)

const pool = fig.trapezoid('MaxPool', {
  pos: [100, 100], size: [100, 50],
  fill: '#e8f5e9', topRatio: 0.55
})
梯形示例

文本 (Text)

const label = fig.text('**粗体** 和 *斜体*', {
  pos: [100, 50], fontSize: 14
})
文本示例

图片 (Image)

const img = fig.image('./photo.png', {
  pos: [100, 50], size: [120, 80]
})
图片示例

3D 图形

圆柱体 (Cylinder)

适合表示数据库和 CNN 特征图。depth 控制椭圆比例(0-1)。

const db = fig.cylinder('数据库', {
  pos: [50, 50], size: [100, 70],
  fill: '#e8f5e9', depth: 0.2
})
圆柱体示例

长方体 (Cuboid)

3D 方块,适合表示张量和数据体。depth 为挤出距离(像素)。

const tensor = fig.cuboid('特征图', {
  pos: [50, 50], size: [80, 60],
  fill: '#fff8e1', depth: 18
})
长方体示例

球体 (Sphere)

const node = fig.sphere('注意力', {
  pos: [100, 100], r: 35,
  fill: '#e0f7fa'
})
球体示例

堆叠层 (Stack)

多层堆叠效果。count 设置层数,stackOffset 控制每层偏移量。

const layers = fig.stack('Conv ×4', {
  pos: [50, 50], size: [100, 60],
  fill: '#ede7f6', count: 4,
  stackOffset: [6, -6]
})
堆叠层示例

ElementConfig

所有属性均为可选,适用于任何元素类型。

属性类型说明
pos[x, y]位置(像素或 '%')
size[w, h]尺寸(像素或 '%')
fillstring填充颜色。'none' = 透明
fillOpacitynumber填充透明度(0-1)
colorstring主题色(同时设置边框和字体颜色)
strokestring | StrokeConfig边框。'none' = 无边框
radiusnumber圆角半径(矩形)
rnumber半径(圆形/球体,默认: 30)
opacitynumber整体透明度(0-1)
shadowboolean | ShadowConfig阴影效果
paddingnumber内边距
fontSizenumber字号(像素)
fontFamilystring字体族
fontColorstring文字颜色
fontWeightstring | number字重
boldbooleanfontWeight: 'bold' 的简写
topRationumber梯形上下底比例(0-1,默认: 0.6)
depthnumber圆柱体:椭圆比例(0.15)。长方体:挤出距离(15px)
countnumber堆叠层数(默认: 3)
stackOffset[dx, dy]每层偏移量(默认: [6, -6])
StrokeConfig: { color?: string, width?: number, dash?: number[] }
虚线示例:[6, 3] = 虚线,[2, 2] = 点线
ShadowConfig: { dx?: number, dy?: number, blur?: number, color?: string }
使用 shadow: true 启用默认阴影,或传入配置对象自定义。

嵌套容器

任何元素都可以包含子元素。子元素相对于父元素定位:

const parent = fig.rect('容器', {
  pos: [50, 50], size: [200, 150]
})

// 子元素使用百分比相对定位
parent.circle('中心', { pos: ['50%', '50%'], r: 20 })
parent.rect('左上', { pos: [10, 30], size: [60, 30] })
嵌套容器示例

基本箭头

fig.arrow(source, target, config?)

连接两个元素。未指定锚点时自动吸附到最近边缘。

fig.arrow(a, b)  // 最简形式
fig.arrow(a, b, { head: 'stealth', color: '#1565c0' })
基本箭头示例

锚点

精确控制箭头连接位置:

// 简单写法:指定边
fig.arrow(a, b, { from: 'right', to: 'left' })

// 详细写法:指定边 + 边上位置(0-100%)
fig.arrow(a, b, {
  from: { side: 'bottom', at: 30 },  // 底边从左起 30% 处
  to: { side: 'top', at: 70 }         // 顶边从左起 70% 处
})
锚点示例

箭头头部类型

内置 11 种箭头头部样式:

类型说明
triangle实心三角形(默认)
triangle-open空心三角形
stealth尖锐箭头(LaTeX 风格)
veeV 形 >
circle实心圆
circle-open空心圆
diamond实心菱形
diamond-open空心菱形
bar竖线 |
dot小圆点
none无箭头
全部11种箭头头部

路径类型

路径说明额外配置
straight直线(默认)-
curve贝塞尔曲线curve: 弯曲程度(正值=向上)
polyline直角折线cornerRadius: 圆角半径
// 曲线箭头
fig.arrow(a, b, { path: 'curve', curve: 40 })

// 带圆角的折线
fig.arrow(a, b, { path: 'polyline', cornerRadius: 8 })
路径类型示例

样式与标签

fig.arrow(a, b, {
  style: 'dashed',           // 'solid' | 'dashed' | 'dotted'
  color: '#e65100',
  width: 2,
  label: '数据流',
  bidirectional: true,       // 双向箭头
  headSize: 10
})
箭头样式示例

arrows() — 扇出 / 扇入

一次创建多条箭头,支持一对多和多对一:

// 扇出:一个源到多个目标
fig.arrows(source, [targetA, targetB, targetC], {
  head: 'stealth', color: '#1565c0'
})

// 扇入:多个源到一个目标
fig.arrows([srcA, srcB, srcC], target, {
  head: 'triangle', style: 'dashed'
})
扇出扇入示例

fork() — 分支

创建带共享主干的分叉箭头,从一个源分裂到多个目标:

fig.fork(source, [targetA, targetB, targetC], {
  head: 'stealth',
  style: 'solid',
  color: '#333'
})
分支箭头示例
区别: arrows() 从源到每个目标画独立箭头。 fork() 先画一条主干,然后分裂成多个分支 —— 像一棵树。

row()

水平排列元素。第一个元素需要设置 pos

fig.row([a, b, c], { gap: 40 })  // 默认间距: 40px
水平布局示例

col()

垂直排列元素。

fig.col([a, b, c], { gap: 30 })
垂直布局示例

grid()

网格排列元素。

fig.grid([a, b, c, d, e, f], {
  cols: 3,        // 3 列(默认)
  gap: 20,        // 统一间距
  rowGap: 30,     // 单独设置行间距
  colGap: 15      // 单独设置列间距
})
网格布局示例

group()

在元素周围绘制带标签的分组框。需要在布局方法之后调用(需要已确定的位置)。返回一个 Rect,可作为箭头目标使用。

const frame = fig.group([a, b, c], {
  label: '流水线',
  fill: 'rgba(25,118,210,0.05)',
  stroke: { color: '#90caf9', dash: [6, 3] },
  radius: 8,
  padding: 20,
  fontSize: 11,
  fontColor: '#1565c0',
  size: [400, 200]    // 可选固定尺寸(自动居中成员)
})
分组框示例

Markdown 标签格式

所有元素标签支持内联 Markdown 格式:

语法效果字体
**粗体**粗体文字相同字体,加粗
*斜体*斜体文字相同字体,斜体
`代码`等宽字体codeFont (Menlo)
$E=mc^2$数学公式mathFont (Times New Roman)
fig.rect('**Conv2D** $3 \\times 3 \\times 64$', { ... })
fig.text('损失函数: `cross_entropy`', { ... })
Markdown标签示例

导出格式

文件格式根据扩展名自动检测:

扩展名格式引擎
.svgSVG 矢量图内置
.pngPNG 位图sharp
.jpg / .jpegJPEGsharp
.webpWebPsharp
.pdfPDF 文档pdfkit
// SVG
await fig.export('output.svg', { fit: true, margin: 20 })

// 高分辨率 PNG
await fig.export('output.png', { fit: true, scale: 3, margin: 30 })

// 获取 SVG 字符串(不保存文件)
const svg = fig.render({ fit: true })

ExportOptions

属性类型默认值说明
fitbooleanfalse自动裁剪到内容边界
marginnumber20裁剪边距(fit=true 时生效,像素)
scalenumber2分辨率倍数(仅位图格式)
qualitynumber90JPG/WebP 质量(1-100)

导出格式展示

一份源码,所有格式。点击下方标签对比不同格式的输出效果:

SVG 导出
.svg
fig.export('flowchart.svg')
  • 矢量格式 — 无限缩放
  • 文件体积最小
  • 保留完整画布大小
PNG 导出
.png
fig.export('flowchart.png')
  • 默认 2 倍分辨率
  • 白色背景
  • 完整画布大小
JPG 导出
.jpg
fig.export('flowchart.jpg', {
  fit: true, margin: 20
})
  • fit: true 自动裁切
  • 内容周围 20px 边距
  • 质量: 90(可调)
PNG 裁切导出
.png 裁切
fig.export('flowchart-fit.png', {
  fit: true, margin: 20
})
  • fit: true 自动裁剪到内容
  • 去除多余空白区域
  • 嵌入文档时效果最佳
透明背景导出
.png 透明
// 不设 bg = 透明背景
const fig = new Figure(800, 350)
fig.export('out.png', { fit: true })
  • 省略 bg 即为透明
  • 棋盘格 = Alpha 通道
  • 叠加使用效果极佳
WebP 导出
.webp
fig.export('flowchart.webp', {
  fit: true, margin: 20
})
  • 现代格式,体积更小
  • 支持透明度
  • 适合网页发布

MCP 集成

Figcraft 内置 MCP(Model Context Protocol)服务端。Claude Code、Cursor 等 AI 智能体可以无需编写代码,直接生成图表。

配置

添加到 Claude Code 或 Cursor 的 MCP 设置中:

{
  "mcpServers": {
    "figcraft": {
      "command": "npx",
      "args": ["figcraft-mcp"]
    }
  }
}

然后用自然语言描述你的图表即可:"画一个 Transformer 架构图,包含编码器和解码器堆叠"

MCP 工具

工具说明
create_diagram根据 JSON 规范创建图表。返回 SVG 并可选导出到文件。
get_element_types获取完整 API 文档。AI 首先调用此工具了解 API。

JSON 规范格式

create_diagram 工具接受以下 JSON 结构:

{
  "width": 800,
  "height": 400,
  "bg": "#ffffff",
  "fontFamily": "Arial",
  "autoAlign": true,
  "elements": [
    {
      "id": "a",
      "type": "rect",
      "label": "输入",
      "pos": [50, 100],
      "size": [120, 60],
      "fill": "#e3f2fd",
      "radius": 6
    },
    {
      "id": "b",
      "type": "rect",
      "label": "输出",
      "pos": [300, 100],
      "size": [120, 60],
      "fill": "#c8e6c9"
    }
  ],
  "arrows": [
    {
      "from": "a",
      "to": "b",
      "fromSide": "right",
      "toSide": "left",
      "label": "data",
      "head": "stealth"
    }
  ],
  "groups": [
    {
      "members": ["a", "b"],
      "label": "流水线",
      "padding": 20,
      "stroke": "#999"
    }
  ],
  "layouts": [
    { "type": "row", "elements": ["a", "b"], "gap": 40 }
  ],
  "fanArrows": [
    { "from": "src", "to": ["a", "b", "c"] }
  ],
  "forks": [
    { "from": "root", "to": ["x", "y", "z"] }
  ],
  "export": {
    "path": "output.svg",
    "fit": true,
    "margin": 20
  }
}

Figure 类 — 所有方法

方法返回值说明
fig.rect(label, config?)Rect创建矩形
fig.circle(label, config?)Circle创建圆形
fig.text(content, config?)Text创建文本标签
fig.image(src, config?)Image创建图片
fig.diamond(label, config?)Diamond创建菱形
fig.trapezoid(label, config?)Trapezoid创建梯形
fig.cylinder(label, config?)Cylinder创建 3D 圆柱体
fig.cuboid(label, config?)Cuboid创建 3D 长方体
fig.sphere(label, config?)Sphere创建 3D 球体
fig.stack(label, config?)Stack创建堆叠层
fig.arrow(src, tgt, config?)void单条箭头
fig.arrows(src, tgt, config?)void扇出 / 扇入
fig.fork(src, targets, config?)void分支箭头
fig.row(els, opts?)void水平布局
fig.col(els, opts?)void垂直布局
fig.grid(els, opts?)void网格布局
fig.group(members, config?)Rect分组框
fig.font(name, source?)void注册字体
fig.render(opts?)string渲染为 SVG 字符串
fig.export(path, opts?)Promise导出到文件

ElementConfig — 完整参考

属性类型默认值说明
pos[PosValue, PosValue]-位置 [x, y],像素或 '%'
size[PosValue, PosValue]自动尺寸 [宽, 高]
fillstring-填充颜色。'none' = 透明
fillOpacitynumber1填充透明度(0-1)
colorstring-主题色(边框 + 字体颜色)
strokestring | StrokeConfig-边框配置
radiusnumber0圆角半径(矩形)
rnumber30圆形/球体半径
opacitynumber1整体透明度
shadowboolean | ShadowConfigfalse阴影效果
paddingnumber-内边距
fontSizenumber14字号(像素)
fontFamilystring继承字体族
fontColorstring#000文字颜色
fontWeightstring | numbernormal字重
boldbooleanfalse加粗简写
topRationumber0.6梯形比例
depthnumber因类型而异3D 深度
countnumber3堆叠层数
stackOffset[number, number][6, -6]堆叠偏移

ArrowConfig — 完整参考

属性类型默认值说明
fromAnchorSpec自动源锚点
toAnchorSpec自动目标锚点
labelstring-文本标签
labelOffsetnumber自动标签偏移量
stylestring'solid''solid' | 'dashed' | 'dotted'
colorstring'#000'箭头颜色
widthnumber1.5线宽
headArrowHead'triangle'头部类型
headSizenumber自动头部大小
bidirectionalbooleanfalse双向箭头
pathArrowPath'straight'路径类型
curvenumber0弯曲程度
cornerRadiusnumber0折线圆角半径

ExportOptions — 完整参考

属性类型默认值说明
scalenumber2分辨率倍数(位图格式)
fitbooleanfalse自动裁剪到内容
marginnumber20fit=true 时的边距(像素)
qualitynumber90JPG/WebP 质量(1-100)