模块3: 图形元素与样式系统
掌握基础图形类型与 CSS 兼容的样式机制
1. 基础图形一览
| 图形 | 类名 | 说明 |
|---|
| 圆 | Circle | 圆心 (cx,cy) + 半径 r |
| 椭圆 | Ellipse | 圆心 + rx, ry |
| 矩形 | Rect | x, y, width, height, 支持 radius 圆角 |
| 直线 | Line | (x1,y1)-(x2,y2) |
| 折线 | Polyline | points 点数组 |
| 多边形 | Polygon | points 封闭多边形 |
| 路径 | Path | SVG path d 语法 |
| 文本 | Text | text, fontSize, fontFamily 等 |
| 图片 | Image | src, width, height |
| HTML | HTML | 嵌入 HTML DOM |
2. 各图形用法示例
2.1 Circle 圆
const circle = new Circle({
style: {
cx: 200, cy: 150, r: 80,
fill: '#1890ff',
stroke: '#fff',
lineWidth: 2,
},
});
2.2 Rect 矩形
const rect = new Rect({
style: {
x: 50, y: 50, width: 200, height: 100,
fill: '#52c41a',
radius: 8, // 或数组 [tl, tr, br, bl]
},
});
2.3 Path 路径
const path = new Path({
style: {
d: 'M 10,80 Q 95,10 180,80 T 350,80',
stroke: '#722ed1', lineWidth: 3, fill: 'none',
},
});
// 路径命令: M(移动) L(直线) H(水平) V(垂直)
// C(三次贝塞尔) Q(二次贝塞尔) A(圆弧) Z(闭合)
2.4 Text / Image / Line / Polyline / Polygon
const text = new Text({ style: {
x: 100, y: 50, text: 'Hello',
fontSize: 24, fill: '#fff', textAlign: 'center',
}});
const img = new Image({ style: {
x: 0, y: 0, width: 200, height: 150, src: 'photo.png',
}});
const line = new Line({ style: {
x1:0, y1:0, x2:200, y2:100, stroke:'red', lineWidth:2,
}});
const polyline = new Polyline({ style: {
points: [[10,10],[50,80],[100,30]], stroke: 'orange',
}});
const polygon = new Polygon({ style: {
points: [[100,10],[40,198],[190,78]],
fill: 'rgba(255,0,0,0.3)',
}});
3. 通用样式属性
| 属性 | 类型 | 说明 |
|---|
fill | string/Gradient/Pattern | 填充 |
stroke | string | 描边色 |
lineWidth | number | 描边宽 |
opacity | 0-1 | 整体透明度 |
fillOpacity | 0-1 | 填充透明度 |
strokeOpacity | 0-1 | 描边透明度 |
lineDash | number[] | 虚线 |
lineCap | butt|round|square | 线端 |
lineJoin | miter|round|bevel | 连接 |
visibility | visible|hidden | 可见性 |
cursor | string | 鼠标样式 |
zIndex | number | 层级 |
pointerEvents | string | 指针事件 |
4. 渐变与图案填充
4.1 线性渐变
// 简写: l(角度) 位置:颜色 ...
circle.style.fill = 'l(0) 0:#ff0000 0.5:#00ff00 1:#0000ff';
// CSS 标准
circle.style.fill = 'linear-gradient(90deg, red, blue)';
4.2 径向渐变
circle.style.fill = 'r(0.5, 0.5, 1) 0:#ff0000 1:#0000ff';
4.3 阴影与滤镜
rect.style.shadowColor = 'rgba(0,0,0,0.5)';
rect.style.shadowBlur = 15;
circle.style.filter = 'blur(5px)';
circle.style.filter = 'drop-shadow(4px 4px 10px black)';
5. CSS 值类型体系
| 类型 | 说明 | 示例 |
|---|
CSSUnitValue | 带单位数值 | 50px, 2em |
CSSRGB | 颜色 | #ff0000, rgb(255,0,0) |
CSSGradientValue | 渐变 | linear-gradient(...) |
CSSKeywordValue | 关键字 | visible, hidden |
6. 样式继承与自定义属性
// 部分属性支持继承 (fontSize, fontFamily, fill 等)
const group = new Group({ style: { fontSize: 16, fill: '#333' } });
const text = new Text({ style: { text: '继承字号' } });
group.appendChild(text); // text 自动继承 fontSize=16
// 注册自定义属性(支持动画插值)
CSS.registerProperty({
name: 'angle',
inherits: false,
initialValue: '0',
interpolable: true,
syntax: PropertySyntax.NUMBER,
});