Canvas
声明式 2D 原生 SwiftUI 矢量画布,支持 9 种图元、线性/径向/角度渐变、虚线描边、任意支点旋转与本地点击坐标(onClickAt),轻松绘制机械表盘、指南针、音频频谱、自定义仪表盘与像素艺术。
签名#
签名
<Canvas
viewWidth={160}
viewHeight={160}
ops={[
{ op: "circle", cx: 80, cy: 80, r: 72,
stroke: "theme.divider",
lineWidth: 2 },
{ op: "line", x1: 80, y1: 80,
x2: 80, y2: 26,
stroke: "theme.accent",
lineWidth: 3, lineCap: "round",
rotateDeg: 45,
pivotX: 80, pivotY: 80 },
]}
/>
逻辑画布 160×160 · 2 条图元
Canvas 属性#
opsCanvasOp[]必填- 按顺序从底到顶绘制的声明式矢量指令数组。建议用
useMemo缓存计算结果。 viewWidthnumber可选- 虚拟逻辑坐标系宽度;省略时直接按组件实际渲染宽度(pt)映射。
viewHeightnumber可选- 虚拟逻辑坐标系高度;配合
viewWidth可像 SVGviewBox一样无失真自适应任何尺寸。 onClickAtfunction可选- 来自
StyleProps:回调({ x, y, width, height }) => void(单位 pt),可实现可交互圆盘、调色盘或棋盘。
支持的 9 种 CanvasOp 图元#
每条指令都是一个普通对象,通过 op 指定要绘制的形状:
rect矩形op: "rect"- 必填字段:
x、y、w、h。 roundedRect圆角矩形op: "roundedRect"- 必填字段:
x、y、w、h、r(圆角半径)。 circle圆形op: "circle"- 必填字段:
cx、cy(圆心)、r(半径)。 ellipse椭圆op: "ellipse"- 必填字段:
cx、cy、rx(水平半轴)、ry(垂直半轴)。 arc圆弧op: "arc"- 字段:
cx、cy、r、startDeg、endDeg、可选anticlockwise(0° 指向 3 点钟方向,顺时针增加)。 line线段op: "line"- 必填字段:
x1、y1、x2、y2;配合rotateDeg、pivotX、pivotY与lineCap: "round"画表针非常顺手。 polyline折线op: "polyline"- 字段:
points(坐标数组[[x, y], ...]),可选closed: true自动首尾闭合。 polygon多边形op: "polygon"- 字段:
points(坐标数组[[x, y], ...]),自动闭合为多边形。 text矢量文字op: "text"- 字段:
x、y、text,可选fontSize、fontWeight、fontDesign、italic、align。
通用绘制样式与变换字段(所有图元均可用)#
fillstring可选- 单色填充色(语义令牌或十六进制)。
fillGradientGradientSpec可选- 渐变填充
{ kind?: "linear" | "radial" | "angular", colors, stops?, x1?, y1?, x2?, y2?, cx?, cy?, r? }。 strokestring可选- 描边颜色。
strokeGradientGradientSpec可选- 渐变描边对象(格式同
fillGradient)。 lineWidthnumber可选- 描边粗细(pt)。
lineCapstring可选- 线段端点样式:
"butt"、"round"或"square"。 dashnumber[]可选- 虚线节奏数组,例如
[4, 4]。 dashPhasenumber可选- 虚线相位偏移量。
rotateDegnumber可选- 顺时针旋转角度(度)。
pivotXnumber可选- 旋转支点的 X 坐标(配合
rotateDeg使用)。 pivotYnumber可选- 旋转支点的 Y 坐标(配合
rotateDeg使用)。 opacitynumber可选- 单个图元的不透明度(
0–1)。
示例:矢量指针模拟表盘#
TSX
const ops: CanvasOp[] = [
{ op: "circle", cx: 80, cy: 80, r: 70,
fill: "theme.faint",
stroke: "theme.divider" },
...hourTicks(12),
{ op: "line", x1: 80, y1: 80,
x2: 80, y2: 44, stroke: "theme.ink",
lineWidth: 4, rotateDeg: 305 },
{ op: "line", x1: 80, y1: 80,
x2: 80, y2: 28, stroke: "theme.ink",
lineWidth: 2.5, rotateDeg: 56 },
{ op: "line", x1: 80, y1: 92,
x2: 80, y2: 24, stroke: "theme.accent",
lineWidth: 1.5, rotateDeg: 180 },
{ op: "circle", cx: 80, cy: 80, r: 4,
fill: "theme.accent" },
];
<Canvas
viewWidth={160}
viewHeight={160}
ops={ops}
/>
矢量指针模拟表盘