@json-render/image 是 json-render 项目提供的一个图片渲染器,用于把 JSON 规格(spec)转换为 SVG 和 PNG 图片,转换过程基于 Satori 实现。
用途
该包用于根据 JSON 结构生成图片,资料中提到的典型场景包括从 JSON 规格生成 OG 图片(OG images)。
主要能力
- 将 JSON spec 渲染为 SVG 字符串或 PNG 数据。
- 提供标准组件集合,用于构建图片布局与内容。
- 支持通过目录(catalog)机制定义和扩展自定义组件。
标准组件
资料列出的标准组件如下:
- Frame(Root 类):根容器,定义宽、高、背景,必须作为根节点。
- Box(Layout 类):带内边距、外边距、边框、绝对定位的容器。
- Row(Layout 类):水平 flex 布局。
- Column(Layout 类):垂直 flex 布局。
- Heading(Content 类):h1-h4 标题文本。
- Text(Content 类):完整样式的正文文本。
- Image(Content 类):来自 URL 的图片。
- Divider(Decorative 类):水平分隔线。
- Spacer(Decorative 类):空的垂直间距。
使用方式
资料给出以下用法示例(代码保持原样):
快速开始:
import { renderToPng } from "@json-render/image/render";
import type { Spec } from "@json-render/core";
const spec: Spec = {
root: "frame",
elements: {
frame: {
type: "Frame",
props: { width: 1200, height: 630, backgroundColor: "#1a1a2e" },
children: ["heading"],
},
heading: {
type: "Heading",
props: { text: "Hello World", level: "h1", color: "#ffffff" },
children: [],
},
},
};
const png = await renderToPng(spec, {
fonts: [{ name: "Inter", data: fontData, weight: 400, style: "normal" }],
});
使用标准组件:
import { defineCatalog } from "@json-render/core";
import { schema, standardComponentDefinitions } from "@json-render/image";
export const imageCatalog = defineCatalog(schema, {
components: standardComponentDefinitions,
});
添加自定义组件:
import { z } from "zod";
const catalog = defineCatalog(schema, {
components: {
...standardComponentDefinitions,
Badge: {
props: z.object({ label: z.string(), color: z.string().nullable() }),
slots: [],
description: "A colored badge label",
},
},
});
关键导出
- renderToSvg:将 spec 渲染为 SVG 字符串。
- renderToPng:将 spec 渲染为 PNG buffer(需要 @resvg/resvg-js)。
- schema:图片元素 schema。
- standardComponents:预构建的组件注册表。
- standardComponentDefinitions:用于 AI 提示的目录定义。
子路径导出
- @json-render/image:完整包,包含 schema、组件、渲染函数。
- @json-render/image/server:仅包含 schema 与目录定义(不含 React/Satori)。
- @json-render/image/catalog:标准组件定义与类型。
- @json-render/image/render:仅包含渲染函数。
适用场景
适用于需要使用 JSON 数据程序化生成图片、特别是 OG 图片等场景,并可通过标准组件与自定义组件灵活扩展内容结构。
限制
- 渲染 PNG 需要依赖 @resvg/resvg-js。
- 渲染时需提供字体数据。 资料未提供收费、价格、平台等信息,暂未提供。