模块3: 图形元素与样式系统

掌握基础图形类型与 CSS 兼容的样式机制

1. 基础图形一览

图形类名说明
Circle圆心 (cx,cy) + 半径 r
椭圆Ellipse圆心 + rx, ry
矩形Rectx, y, width, height, 支持 radius 圆角
直线Line(x1,y1)-(x2,y2)
折线Polylinepoints 点数组
多边形Polygonpoints 封闭多边形
路径PathSVG path d 语法
文本Texttext, fontSize, fontFamily 等
图片Imagesrc, width, height
HTMLHTML嵌入 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. 通用样式属性

属性类型说明
fillstring/Gradient/Pattern填充
strokestring描边色
lineWidthnumber描边宽
opacity0-1整体透明度
fillOpacity0-1填充透明度
strokeOpacity0-1描边透明度
lineDashnumber[]虚线
lineCapbutt|round|square线端
lineJoinmiter|round|bevel连接
visibilityvisible|hidden可见性
cursorstring鼠标样式
zIndexnumber层级
pointerEventsstring指针事件

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,
});