# @sch39/canvas-text-paragraphs 中文文档

规范地址：https://npmcn.com/package/%40sch39/canvas-text-paragraphs/

版本：2\.0\.0
npm 元数据更新时间：2026-11-02T07:42:35.722Z
中文译文更新时间：2026-11-02T10:56:40.386Z
软件包许可：MIT

本文由上游 README 机器翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40sch39/canvas-text-paragraphs
原文对照：https://npmcn.com/package/%40sch39/canvas-text-paragraphs/?lang=original
项目主页：https://github.com/Sch39/canvas-text-paragraphs#readme
源码仓库：https://github.com/Sch39/canvas-text-paragraphs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：89.4 kB，10 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2024-06-30T00:42:03.834Z
- 最新版本发布：2026-11-02T07:42:35.561Z
- 已发布版本数：5（近 12 个月 1 个）

## 中文简介

一个轻量级JavaScript库，旨在简化在画布环境中管理文本段落的过程。它提供了一套全面的工具来对齐、缩进和间隔文本段落，使开发人员能够创建可视化

## 安装

```sh
npm install @sch39/canvas-text-paragraphs
```

也可以使用：`pnpm add @sch39/canvas-text-paragraphs`、`yarn add @sch39/canvas-text-paragraphs`、`bun add @sch39/canvas-text-paragraphs`

## README

# 画布文本段落

Canvas Text paragraph是一个JavaScript库，旨在促进在HTML5画布元素上呈现格式化段落。它提供了在画布内管理文本对齐、缩进、行间距和垂直定位的功能。

## 安装

你可以通过npm安装Canvas Text段落：

```
npm install @sch39/canvas-text-paragraphs
```

或者来自unpkg

```
<script src="https://unpkg.com/@sch39/canvas-text-paragraphs@latest/dist/index.umd.js"></script>
```

该脚本公开了全局函数 `canvasTextParagraphs`.

## 使用

### 导入库

```
import canvasTextParagraphs from '@sch39/canvas-text-paragraphs'
```

### 例子

```
import canvasTextParagraphs from '@sch39/canvas-text-paragraphs';

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

const text = `
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla facilisi. Integer id elit varius, commodo tortor eget,
lacinia ligula. Ut interdum nisi non dui pretium faucibus.
`;

canvasTextParagraphs(text, ctx, {
  align: 'center',
  verticalAlign: 'middle',
  spaceBeforeParagraph: 20,
  spaceAfterParagraph: 20,
  indent: {
    type: 'firstLine',
    by: 40,
  },
});


```

### 打印稿

类型定义捆绑在一起(`index.d.ts`),没有 `@types` 包需要:

```ts
import canvasTextParagraphs from '@sch39/canvas-text-paragraphs'
import type { Options } from '@sch39/canvas-text-paragraphs'

const ctx = (document.getElementById('myCanvas') as HTMLCanvasElement).getContext('2d')!

const options: Options = {
  width: 400,
  align: 'justify',
  indent: { type: 'firstLine', by: 4 },
}

canvasTextParagraphs('Hello world', ctx, options)
```

## 演示

链接: [点击这里](https://codepen.io/editor/sch39/pen/01a19811-e040-763d-8fdb-abfe9b42480c)

现场演示: [点击这里](https://codepen.io/sch39/pen/abrgPEM)

## 函数参数

-   **文本** （string）：要呈现的文本内容。
-   **ctx** （CanvasRenderingContext2D）：画布渲染上下文。
-   **选项** （object）：可选配置对象，具有以下属性：
    -   **宽度** （number或‘auto’，默认值：‘auto’）：文本框的宽度。 `'auto'` =画布的其余部分 `xStart`.
    -   **高度** （number或‘auto’，默认值：‘auto’）：文本框的高度。 `'auto'` =画布的其余部分 `yStart`。下面的线条 `yStart + height` 没有画出来。
    -   **xStart** （数字，默认值：0）：文本框的左边缘。
    -   **yStart** （数字，默认值：0）：文本框的上边缘。
    -   **对齐** （string, default: 'left‘）：水平文本对齐（’left', 'center', 'right', 'justify'）。
    -   **verticalAlign** （string, default: 'top‘）：垂直文本对齐（’top', 'middle', 'bottom'）。
    -   **基线** （string, default: 'top‘）：文本基线对齐（’top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'）。
    -   **spaceBeforeParagraph** （数字，默认值：0）：每段前的空格。
    -   **spaceAfterParagraph** （数字，默认值：0）：每个段落后面的空格。
    -   **lineSpacing** （number或‘auto’， default: 'auto'）：行间距因子（乘以行高），或 `'auto'` 用于自动间隔。
    -   **缩进** （object）：与默认值合并，所以你可以只传递你需要的键(例如： `{ type: 'firstLine' }` 使用 `by: 0`， `{ by: 4 }` 使用 `type: 'none'`）。
        -   **类型** （string, default: 'none‘）：缩进类型（’none', 'firstLine', 'hanging'）。
        -   **由** （number，默认值：0）：缩进量，表示当前字体中的空格字符数。

文本框为 `[xStart, xStart + width] x [yStart, yStart + height]`。自动换行, `align`， `indent` 和 `verticalAlign` 都在这个方框内计算。

### 行为笔记

-   段落之间用 `\n`。每一段都是逐字剪裁和包装的；一个比 `width` 不裂开，溢出盒子。
-   段落的最后一行永远不会对齐（它是左对齐的）。
-   画布状态是隔离的： `textBaseline` 和 `textAlign` 在绘制时设置并在之后恢复，因此您自己的值保持不变。集 `ctx.font` 和 `ctx.fillStyle` 之前调用。

### 错误

无效输入引发 `Error` 带着信息 `Invalid <name>`例如： `Invalid text`， `Invalid ctx`， `Invalid Align`， `Invalid width` 或者 `Invalid indent.by`. `ctx` 一定是。 `CanvasRenderingContext2D`.

## 开发

```
npm install
npm test        # vitest
npm run build   # dist/ (cjs, es, umd)
npm run dev     # vite dev server
```

## 从1.x迁移

在2.0.0, `width` 和 `height` 是 **大小** 文本框的。在1。X它们是绝对的右/底边缘(`xStart + size`）。

-   如果 `xStart` 和 `yStart` 是 `0` （或省略），什么都没有改变。
-   如果你设置 `xStart`/`yStart` 一起 `width`/`height`，从旧值中减去起始值：

```js
// 1.x: right edge at x = 300, bottom edge at y = 200
canvasTextParagraphs(text, ctx, { xStart: 50, yStart: 20, width: 300, height: 200 })

// 2.0.0: same box
canvasTextParagraphs(text, ctx, { xStart: 50, yStart: 20, width: 250, height: 180 })
```

-   `'auto'` 仍然填满画布，现在从 `xStart`/`yStart`.
-   `verticalAlign: 'middle' | 'bottom'` 现在中心/底部在框内，而不是相对于画布原点。

1.1.0以来的其他行为变化：

-   完全符合框宽的行不再提前换行（不再测量尾随空间），因此换行可能与1.x略有不同。
-   `indent` 与其默认值合并； `{ type: 'firstLine' }` 没有 `by` 不再投掷。
-   `textBaseline` 和 `textAlign` 将在每次调用后恢复您的上下文。
-   UMD构建只公开全局 `canvasTextParagraphs`，现在可以在任何地方导入ES构建 `self` 未定义（节点，SSR）。

## 许可证

本项目使用麻省理工学院许可协议。看到 [许可证](https://npmcn.com/package/%40sch39/canvas-text-paragraphs/LICENSE) 文件查看详细信息。

## 常见问题

### @sch39/canvas-text-paragraphs 是什么？

一个轻量级JavaScript库，旨在简化在画布环境中管理文本段落的过程。它提供了一套全面的工具来对齐、缩进和间隔文本段落，使开发人员能够创建可视化

### 如何安装 @sch39/canvas-text-paragraphs？

在项目目录运行 npm install @sch39/canvas-text-paragraphs，或使用 pnpm add / yarn add / bun add。

### @sch39/canvas-text-paragraphs 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @sch39/canvas-text-paragraphs 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @sch39/canvas-text-paragraphs 可以商用吗？

@sch39/canvas-text-paragraphs 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @sch39/canvas-text-paragraphs 还在维护吗？

最新版本 2\.0\.0 发布于 2026/11/02（1 天前）；至今共发布 5 个版本，其中过去 12 个月发布了 1 个；首次发布于 2024/06/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

