@codehz/draw-call 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,15 +1,426 @@
1
1
  # @codehz/draw-call
2
2
 
3
- To install dependencies:
3
+ 一个声明式 Canvas 绘图库,提供 Flexbox 布局引擎和组件化渲染系统。使用类似 UI 框架的方式来绘制 Canvas 内容,让 Canvas 绘图变得简单直观。
4
+
5
+ ## ✨ 特性
6
+
7
+ - **Flexbox 布局引擎** - 支持完整的 Flexbox 布局,包括方向、对齐、间距等
8
+ - **组件化渲染** - 提供 Box、Text、Image、Svg、Stack、RichText、CustomDraw、Transform 等组件
9
+ - **丰富的样式支持** - 渐变、阴影、边框、圆角等
10
+ - **文本排版** - 自动换行、省略号、行高控制、富文本支持等
11
+ - **SVG 图形** - 支持矩形、圆形、椭圆、路径等 SVG 图形
12
+ - **2D 变换** - 支持旋转、倾斜等 2D 变换操作
13
+ - **自定义绘制** - 支持自定义 Canvas 绘制逻辑
14
+ - **跨平台** - 支持浏览器和 Node.js 环境
15
+ - **TypeScript** - 完整的类型支持
16
+
17
+ ## 📦 安装
4
18
 
5
19
  ```bash
6
- bun install
20
+ bun install @codehz/draw-call
7
21
  ```
8
22
 
9
- To run:
23
+ ## 🚀 快速开始
10
24
 
11
- ```bash
12
- bun run index.ts
25
+ ### 浏览器环境
26
+
27
+ ```typescript
28
+ import { createCanvas, Box, Text } from "@codehz/draw-call";
29
+
30
+ // 获取 canvas 元素
31
+ const canvasEl = document.getElementById("canvas") as HTMLCanvasElement;
32
+
33
+ // 创建 Canvas 实例
34
+ const canvas = createCanvas({
35
+ width: 400,
36
+ height: 300,
37
+ pixelRatio: window.devicePixelRatio || 1,
38
+ canvas: canvasEl,
39
+ });
40
+
41
+ // 渲染内容
42
+ canvas.render(
43
+ Box({
44
+ width: "fill",
45
+ height: "fill",
46
+ background: "#ffffff",
47
+ padding: 20,
48
+ children: [
49
+ Text({
50
+ content: "Hello, draw-call!",
51
+ font: { size: 24, weight: "bold" },
52
+ color: "#333333",
53
+ }),
54
+ ],
55
+ })
56
+ );
57
+ ```
58
+
59
+ ### Node.js 环境
60
+
61
+ ```typescript
62
+ import { createCanvas, Box, Text } from "@codehz/draw-call";
63
+ import { createNodeCanvas } from "@codehz/draw-call/node";
64
+
65
+ // 创建 Canvas 实例
66
+ const canvas = createNodeCanvas({
67
+ width: 400,
68
+ height: 300,
69
+ pixelRatio: 2,
70
+ });
71
+
72
+ // 渲染内容
73
+ canvas.render(
74
+ Box({
75
+ width: "fill",
76
+ height: "fill",
77
+ background: "#ffffff",
78
+ padding: 20,
79
+ children: [
80
+ Text({
81
+ content: "Hello, draw-call!",
82
+ font: { size: 24, weight: "bold" },
83
+ color: "#333333",
84
+ }),
85
+ ],
86
+ })
87
+ );
88
+
89
+ // 保存为图片
90
+ const buffer = await canvas.toBuffer("image/png");
91
+ await Bun.write("output.png", buffer);
92
+ ```
93
+
94
+ ## 📚 组件
95
+
96
+ ### Box
97
+
98
+ 容器组件,支持 Flexbox 布局和丰富的样式。
99
+
100
+ ```typescript
101
+ Box({
102
+ width: 200,
103
+ height: 100,
104
+ background: "#ffffff",
105
+ border: { radius: 8, width: 1, color: "#e0e0e0" },
106
+ shadow: { offsetY: 2, blur: 8, color: "rgba(0,0,0,0.08)" },
107
+ padding: 20,
108
+ direction: "row",
109
+ justify: "center",
110
+ align: "center",
111
+ children: [...],
112
+ })
113
+ ```
114
+
115
+ ### Text
116
+
117
+ 文本组件,支持自动换行、行高控制等。
118
+
119
+ ```typescript
120
+ Text({
121
+ content: "这是一段文本",
122
+ font: { size: 16, weight: "bold", family: "sans-serif" },
123
+ color: "#333333",
124
+ align: "center",
125
+ lineHeight: 1.5,
126
+ wrap: true,
127
+ maxLines: 3,
128
+ ellipsis: true,
129
+ });
130
+ ```
131
+
132
+ ### RichText
133
+
134
+ 富文本组件,支持同时展示多种样式的文本,每个文本段落可以有不同的字体、颜色、背景、装饰等。
135
+
136
+ ```typescript
137
+ RichText({
138
+ spans: [
139
+ {
140
+ text: "普通文本 ",
141
+ color: "#333333",
142
+ },
143
+ {
144
+ text: "加粗文本 ",
145
+ font: { size: 16, weight: "bold" },
146
+ color: "#333333",
147
+ },
148
+ {
149
+ text: "彩色文本 ",
150
+ font: { size: 16, weight: "bold" },
151
+ color: "#667eea",
152
+ },
153
+ {
154
+ text: "带背景 ",
155
+ color: "#ffffff",
156
+ background: "#764ba2",
157
+ },
158
+ {
159
+ text: "带下划线",
160
+ underline: true,
161
+ color: "#333333",
162
+ },
163
+ {
164
+ text: "删除线",
165
+ strikethrough: true,
166
+ color: "#999999",
167
+ },
168
+ ],
169
+ lineHeight: 1.5,
170
+ align: "left",
171
+ maxLines: 5,
172
+ ellipsis: true,
173
+ });
174
+ ```
175
+
176
+ ### Image
177
+
178
+ 图片组件,支持多种适配模式。
179
+
180
+ ```typescript
181
+ Image({
182
+ src: imageBitmap,
183
+ width: 200,
184
+ height: 150,
185
+ fit: "cover", // contain | cover | fill | none | scale-down
186
+ position: { x: "center", y: "center" },
187
+ border: { radius: 8 },
188
+ });
189
+ ```
190
+
191
+ ### Svg
192
+
193
+ SVG 图形组件,支持多种图形元素。
194
+
195
+ ```typescript
196
+ import { svg } from "@codehz/draw-call";
197
+
198
+ Svg({
199
+ width: 200,
200
+ height: 100,
201
+ viewBox: { width: 200, height: 100 },
202
+ children: [
203
+ svg.rect({ x: 10, y: 10, width: 50, height: 30, fill: "#667eea" }),
204
+ svg.circle({ cx: 100, cy: 50, r: 20, fill: "#764ba2" }),
205
+ svg.path({ d: "M150 50 Q170 30, 190 50", stroke: { color: "#333", width: 2 } }),
206
+ ],
207
+ });
208
+ ```
209
+
210
+ ### Stack
211
+
212
+ 堆叠组件,子元素绝对定位。
213
+
214
+ ```typescript
215
+ Stack({
216
+ width: 200,
217
+ height: 200,
218
+ align: "center",
219
+ justify: "center",
220
+ children: [
221
+ Box({ width: 100, height: 100, background: "#ff0000" }),
222
+ Box({ width: 50, height: 50, background: "#00ff00" }),
223
+ ],
224
+ });
225
+ ```
226
+
227
+ ### Transform
228
+
229
+ 2D 变换组件,支持旋转、倾斜等变换操作。
230
+
231
+ ```typescript
232
+ Transform({
233
+ children: Box({
234
+ width: 100,
235
+ height: 100,
236
+ background: "#667eea",
237
+ }),
238
+ transform: {
239
+ rotate: Math.PI / 4, // 旋转 45 度
240
+ },
241
+ transformOrigin: ["50%", "50%"], // 变换原点
242
+ });
243
+ ```
244
+
245
+ ### CustomDraw
246
+
247
+ 自定义绘制组件,提供原生 Canvas 上下文进行自定义绘制。
248
+
249
+ ```typescript
250
+ CustomDraw({
251
+ width: 200,
252
+ height: 100,
253
+ draw: (ctx, options) => {
254
+ // 使用原生 Canvas API 进行绘制
255
+ ctx.fillStyle = "#667eea";
256
+ ctx.fillRect(10, 10, 180, 80);
257
+ ctx.fillStyle = "#ffffff";
258
+ ctx.font = "bold 16px sans-serif";
259
+ ctx.textAlign = "center";
260
+ ctx.fillText("Custom Draw", 100, 60);
261
+ },
262
+ });
263
+ ```
264
+
265
+ ## 🎨 样式
266
+
267
+ ### 尺寸
268
+
269
+ ```typescript
270
+ // 固定像素值
271
+ width: 100;
272
+
273
+ // 百分比
274
+ width: "50%";
275
+
276
+ // 自动计算
277
+ width: "auto";
278
+
279
+ // 填充可用空间
280
+ width: "fill";
281
+ ```
282
+
283
+ ### 颜色
284
+
285
+ ```typescript
286
+ // CSS 颜色字符串
287
+ background: "#ff0000";
288
+ background: "rgb(255, 0, 0)";
289
+ background: "red";
290
+
291
+ // 渐变
292
+ import { linearGradient, radialGradient } from "@codehz/draw-call";
293
+
294
+ // 线性渐变
295
+ background: linearGradient(135, "#667eea", "#764ba2");
296
+
297
+ // 带位置色标的线性渐变
298
+ background: linearGradient(90, [0, "#667eea"], [0.5, "#764ba2"], [1, "#f093fb"]);
299
+
300
+ // 径向渐变
301
+ background: radialGradient({ startX: 0.5, startY: 0.5, endRadius: 0.5 }, "#667eea", "#764ba2");
302
+ ```
303
+
304
+ ### 边框
305
+
306
+ ```typescript
307
+ border: {
308
+ width: 2,
309
+ color: "#e0e0e0",
310
+ radius: 8, // 或 [8, 8, 8, 8] 分别对应左上、右上、右下、左下
311
+ }
312
+ ```
313
+
314
+ ### 阴影
315
+
316
+ ```typescript
317
+ shadow: {
318
+ offsetX: 0,
319
+ offsetY: 4,
320
+ blur: 16,
321
+ color: "rgba(0,0,0,0.12)",
322
+ }
323
+ ```
324
+
325
+ ### 间距
326
+
327
+ ```typescript
328
+ // 四边相同
329
+ padding: 20
330
+ margin: 10
331
+
332
+ // 分别设置
333
+ padding: { top: 10, right: 20, bottom: 10, left: 20 }
334
+ margin: { top: 5, right: 10, bottom: 5, left: 10 }
335
+ ```
336
+
337
+ ## 📐 布局
338
+
339
+ ### Flexbox 布局
340
+
341
+ ```typescript
342
+ Box({
343
+ direction: "row", // row | column
344
+ justify: "center", // flex-start | center | flex-end | space-between | space-around | space-evenly
345
+ align: "center", // flex-start | center | flex-end | stretch | baseline
346
+ gap: 10,
347
+ wrap: true,
348
+ children: [...],
349
+ })
350
+ ```
351
+
352
+ ### 弹性布局
353
+
354
+ ```typescript
355
+ Box({
356
+ direction: "row",
357
+ children: [
358
+ Box({ width: 100 }), // 固定宽度
359
+ Box({ flex: 1 }), // 占据剩余空间
360
+ Box({ flex: 2 }), // 占据 2 份剩余空间
361
+ ],
362
+ });
13
363
  ```
14
364
 
15
- This project was created using `bun init` in bun v1.3.6. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
365
+ ## 🔧 高级用法
366
+
367
+ ### 自定义字体(Node.js)
368
+
369
+ ```typescript
370
+ import { GlobalFonts } from "@napi-rs/canvas";
371
+
372
+ GlobalFonts.registerFromPath("/path/to/font.ttf", "CustomFont");
373
+
374
+ Text({
375
+ content: "自定义字体",
376
+ font: { family: "CustomFont", size: 16 },
377
+ });
378
+ ```
379
+
380
+ ### 导出图片
381
+
382
+ ```typescript
383
+ // 导出为 PNG
384
+ const buffer = await canvas.toBuffer("image/png");
385
+
386
+ // 导出为 JPEG
387
+ const buffer = await canvas.toBuffer("image/jpeg", { quality: 0.9 });
388
+
389
+ // 导出为 WebP
390
+ const buffer = await canvas.toBuffer("image/webp", { quality: 0.8 });
391
+ ```
392
+
393
+ ### 获取布局信息
394
+
395
+ ```typescript
396
+ const layoutNode = canvas.render(
397
+ Box({
398
+ width: 200,
399
+ height: 100,
400
+ children: [...],
401
+ })
402
+ );
403
+
404
+ console.log(layoutNode.layout.width); // 200
405
+ console.log(layoutNode.layout.height); // 100
406
+ console.log(layoutNode.layout.x); // 0
407
+ console.log(layoutNode.layout.y); // 0
408
+ ```
409
+
410
+ ## 📖 示例
411
+
412
+ 查看 [examples](examples) 目录获取更多示例:
413
+
414
+ - [demo.ts](examples/demo.ts) - 浏览器环境演示
415
+ - [card.ts](examples/card.ts) - Node.js 环境卡片示例
416
+ - [richtext.ts](examples/richtext.ts) - 富文本示例
417
+ - [transform.ts](examples/transform.ts) - 2D 变换示例
418
+ - [customdraw.ts](examples/customdraw.ts) - 自定义绘制示例
419
+
420
+ ## 🤝 贡献
421
+
422
+ 欢迎提交 Issue 和 Pull Request!
423
+
424
+ ## 📄 许可证
425
+
426
+ MIT
package/canvas.d.cts CHANGED
@@ -67,6 +67,19 @@ interface Bounds {
67
67
  height: number;
68
68
  }
69
69
  //#endregion
70
+ //#region src/layout/utils/measure.d.ts
71
+ interface MeasureTextResult {
72
+ width: number;
73
+ height: number;
74
+ offset: number;
75
+ ascent: number;
76
+ descent: number;
77
+ }
78
+ interface MeasureContext {
79
+ measureText(text: string, font: FontProps): MeasureTextResult;
80
+ }
81
+ declare function createCanvasMeasureContext(ctx: CanvasRenderingContext2D): MeasureContext;
82
+ //#endregion
70
83
  //#region src/types/layout.d.ts
71
84
  type FlexDirection = "row" | "column" | "row-reverse" | "column-reverse";
72
85
  type JustifyContent = "start" | "end" | "center" | "space-between" | "space-around" | "space-evenly";
@@ -101,12 +114,32 @@ interface ComputedLayout {
101
114
  contentWidth: number;
102
115
  contentHeight: number;
103
116
  }
117
+ interface RichTextSpanSegment {
118
+ text: string;
119
+ font: FontProps;
120
+ color: Color;
121
+ background: Color;
122
+ underline: boolean;
123
+ strikethrough: boolean;
124
+ width: number;
125
+ height: number;
126
+ ascent: number;
127
+ descent: number;
128
+ offset: number;
129
+ }
130
+ interface RichTextLine {
131
+ segments: RichTextSpanSegment[];
132
+ width: number;
133
+ height: number;
134
+ baseline: number;
135
+ }
104
136
  interface LayoutNode {
105
137
  element: Element;
106
138
  layout: ComputedLayout;
107
139
  children: LayoutNode[];
108
140
  lines?: string[];
109
141
  lineOffsets?: number[];
142
+ richLines?: RichTextLine[];
110
143
  }
111
144
  interface LayoutConstraints {
112
145
  minWidth: number;
@@ -116,7 +149,12 @@ interface LayoutConstraints {
116
149
  }
117
150
  //#endregion
118
151
  //#region src/types/components.d.ts
119
- type ElementType = "box" | "text" | "image" | "svg" | "stack";
152
+ type ElementType = "box" | "text" | "richtext" | "image" | "svg" | "stack" | "transform" | "customdraw";
153
+ interface ProxiedCanvasContextOptions {
154
+ inner?: () => void;
155
+ width: number;
156
+ height: number;
157
+ }
120
158
  interface ElementBase {
121
159
  type: ElementType;
122
160
  }
@@ -147,6 +185,27 @@ interface TextProps extends LayoutProps {
147
185
  interface TextElement extends ElementBase, TextProps {
148
186
  type: "text";
149
187
  }
188
+ interface RichTextStyleProps {
189
+ font?: FontProps;
190
+ color?: Color;
191
+ background?: Color;
192
+ underline?: boolean;
193
+ strikethrough?: boolean;
194
+ }
195
+ interface RichTextSpan extends RichTextStyleProps {
196
+ text: string;
197
+ }
198
+ interface RichTextProps extends LayoutProps, RichTextStyleProps {
199
+ spans: RichTextSpan[];
200
+ lineHeight?: number;
201
+ align?: "left" | "center" | "right";
202
+ verticalAlign?: "top" | "middle" | "bottom";
203
+ maxLines?: number;
204
+ ellipsis?: boolean;
205
+ }
206
+ interface RichTextElement extends ElementBase, RichTextProps {
207
+ type: "richtext";
208
+ }
150
209
  interface ImageProps extends LayoutProps {
151
210
  src: ImageBitmap | CanvasImageSource;
152
211
  fit?: "contain" | "cover" | "fill" | "none" | "scale-down";
@@ -168,10 +227,10 @@ interface SvgStyleProps {
168
227
  }
169
228
  interface SvgTransformProps {
170
229
  transform?: {
171
- translate?: [number, number];
230
+ translate?: [number, number]; /** 旋转角度(弧度)或 [angle(弧度), cx, cy](绕点旋转) */
172
231
  rotate?: number | [number, number, number];
173
- scale?: number | [number, number];
174
- skewX?: number;
232
+ scale?: number | [number, number]; /** 水平偏移角度(弧度) */
233
+ skewX?: number; /** 垂直偏移角度(弧度) */
175
234
  skewY?: number;
176
235
  matrix?: [number, number, number, number, number, number];
177
236
  };
@@ -266,7 +325,43 @@ interface StackProps extends LayoutProps {
266
325
  interface StackElement extends ElementBase, StackProps {
267
326
  type: "stack";
268
327
  }
269
- type Element = BoxElement | TextElement | ImageElement | SvgElement | StackElement;
328
+ interface TransformSimpleObject {
329
+ translate?: [number, number];
330
+ /** 旋转角度(弧度)或 [angle(弧度), cx, cy](绕点旋转) */
331
+ rotate?: number | [number, number, number];
332
+ scale?: number | [number, number];
333
+ /** 水平偏移角度(弧度) */
334
+ skewX?: number;
335
+ /** 垂直偏移角度(弧度) */
336
+ skewY?: number;
337
+ }
338
+ interface DOMMatrix2DInit {
339
+ a?: number;
340
+ b?: number;
341
+ c?: number;
342
+ d?: number;
343
+ e?: number;
344
+ f?: number;
345
+ }
346
+ type TransformValue = TransformSimpleObject | DOMMatrix2DInit | [number, number, number, number, number, number];
347
+ interface TransformProps {
348
+ children: Element;
349
+ /** 变换值(rotate/skew 使用弧度) */
350
+ transform?: TransformValue;
351
+ /** 变换原点,默认为 [0, 0](左上角) */
352
+ transformOrigin?: [number | string, number | string];
353
+ }
354
+ interface TransformElement extends ElementBase, TransformProps {
355
+ type: "transform";
356
+ }
357
+ interface CustomDrawProps extends LayoutProps {
358
+ draw: (ctx: CanvasRenderingContext2D, options: ProxiedCanvasContextOptions) => void;
359
+ children?: Element;
360
+ }
361
+ interface CustomDrawElement extends ElementBase, CustomDrawProps {
362
+ type: "customdraw";
363
+ }
364
+ type Element = BoxElement | TextElement | RichTextElement | ImageElement | SvgElement | StackElement | TransformElement | CustomDrawElement;
270
365
  //#endregion
271
366
  //#region src/canvas.d.ts
272
367
  interface CanvasOptions {
@@ -301,4 +396,4 @@ interface DrawCallCanvas {
301
396
  */
302
397
  declare function createCanvas(options: CanvasOptions): DrawCallCanvas;
303
398
  //#endregion
304
- export { AlignItems as A, Color as B, SvgProps as C, SvgTransformProps as D, SvgTextChild as E, LayoutConstraints as F, RadialGradientDescriptor as G, FontProps as H, LayoutNode as I, Spacing as J, Shadow as K, LayoutProps as L, ContainerLayoutProps as M, FlexDirection as N, TextElement as O, JustifyContent as P, Border as R, SvgPolylineChild as S, SvgStyleProps as T, GradientDescriptor as U, ColorStop as V, LinearGradientDescriptor as W, linearGradient as X, StrokeProps as Y, radialGradient as Z, SvgEllipseChild as _, BoxElement as a, SvgPathChild as b, ImageElement as c, StackElement as d, StackProps as f, SvgElement as g, SvgCircleChild as h, createCanvas as i, AlignSelf as j, TextProps as k, ImageProps as l, SvgChild as m, DrawCallCanvas as n, BoxProps as o, SvgAlign as p, Size as q, LayoutSize as r, Element as s, CanvasOptions as t, StackAlign as u, SvgGroupChild as v, SvgRectChild as w, SvgPolygonChild as x, SvgLineChild as y, Bounds as z };
399
+ export { GradientDescriptor as $, SvgRectChild as A, ContainerLayoutProps as B, SvgEllipseChild as C, SvgPolygonChild as D, SvgPathChild as E, TextProps as F, LayoutProps as G, JustifyContent as H, TransformElement as I, Border as J, MeasureContext as K, TransformProps as L, SvgTextChild as M, SvgTransformProps as N, SvgPolylineChild as O, TextElement as P, FontProps as Q, AlignItems as R, SvgElement as S, SvgLineChild as T, LayoutConstraints as U, FlexDirection as V, LayoutNode as W, Color as X, Bounds as Y, ColorStop as Z, StackElement as _, BoxElement as a, StrokeProps as at, SvgChild as b, CustomDrawProps as c, ImageProps as d, LinearGradientDescriptor as et, ProxiedCanvasContextOptions as f, StackAlign as g, RichTextSpan as h, createCanvas as i, Spacing as it, SvgStyleProps as j, SvgProps as k, Element as l, RichTextProps as m, DrawCallCanvas as n, Shadow as nt, BoxProps as o, linearGradient as ot, RichTextElement as p, createCanvasMeasureContext as q, LayoutSize as r, Size as rt, CustomDrawElement as s, radialGradient as st, CanvasOptions as t, RadialGradientDescriptor as tt, ImageElement as u, StackProps as v, SvgGroupChild as w, SvgCircleChild as x, SvgAlign as y, AlignSelf as z };