首页
/ LogicFlow自定义折线边开发指南

LogicFlow自定义折线边开发指南

2025-07-06 06:36:07作者:齐冠琰

LogicFlow作为一款优秀的流程图编辑框架,提供了丰富的边类型支持。本文将深入解析如何基于LogicFlow实现自定义折线边(PolylineEdge),包括箭头样式、文本位置、动画效果等全方位定制。

自定义边的基本结构

在LogicFlow中,自定义边需要同时定义Model和View两个部分:

  1. Model:负责边的数据逻辑,如位置计算、样式定义等
  2. View:负责边的可视化渲染,如SVG图形绘制

示例代码中定义了一个customPolyline类型的边,包含CustomPolylineModelCustomPolyline两个类。

自定义箭头样式

通过重写getEndArrow方法可以实现多种箭头样式:

getEndArrow() {
  const { model } = this.props
  const { properties: { arrowType } } = model
  const { stroke, strokeWidth } = model.getArrowStyle()
  
  // 空心箭头
  if (arrowType === 'empty') {
    return h('path', {
      stroke,
      strokeWidth,
      fill: '#FFF',
      d: 'M -10 0  -20 -5 -30 0 -20 5 z',
    })
  } 
  // 半箭头
  else if (arrowType === 'half') {
    return h('path', {
      stroke,
      strokeWidth,
      d: 'M 0 0 -10 5',
    })
  }
  // 默认实心箭头
  return h('path', {
    stroke,
    strokeWidth,
    fill: stroke,
    d: 'M 0 0 -10 -5 -10 5 z',
  })
}

箭头样式通过properties.arrowType属性控制,开发者可以根据业务需求扩展更多箭头类型。

自定义文本位置

在Model中重写getTextPosition方法可以灵活控制边文本的位置:

getTextPosition(): LogicFlow.Point {
  const { textPosition = 'center' } = this.properties
  const position = super.getTextPosition()
  
  // 获取折线所有点
  const pointsList = this.points.split(' ').map(item => {
    const [x, y] = item.split(',')
    return { x: Number(x), y: Number(y) }
  })
  
  if (textPosition === 'start') {
    // 文本靠近起点
    if (pointsList.length > 1) {
      const { x: x1, y: y1 } = pointsList[0]
      const { x: x2, y: y2 } = pointsList[1]
      // 计算偏移量...
    }
  } 
  else if (textPosition === 'end') {
    // 文本靠近终点
    // 类似起点逻辑...
  }
  
  return position
}

支持三种文本位置:

  • center:默认居中显示
  • start:靠近起点
  • end:靠近终点

自定义动画效果

LogicFlow支持为边添加动画效果,通过以下方式自定义:

// 启用动画
setAttributes() {
  const { openAnimation } = this.properties
  this.isAnimation = !!openAnimation
}

// 自定义动画样式
getEdgeAnimationStyle() {
  const style = super.getEdgeAnimationStyle()
  style.strokeDasharray = '15 5'  // 虚线样式
  style.animationDuration = '10s' // 动画时长
  style.stroke = 'rgb(130, 179, 102)' // 动画颜色
  return style
}

自定义边样式

通过重写getEdgeStyle方法可以自定义边的颜色、宽度等基础样式:

getEdgeStyle() {
  const style = super.getEdgeStyle()
  const { edgeWeight, highlight } = this.properties
  style.strokeWidth = edgeWeight ? 5 : 3  // 线宽
  style.stroke = highlight ? 'red' : 'black' // 颜色
  return style
}

实际应用建议

  1. 业务属性扩展:可以通过properties属性扩展各种业务属性,如arrowTypetextPosition
  2. 性能优化:复杂的自定义边应考虑性能影响,避免过度绘制
  3. 交互增强:可以结合LogicFlow的事件系统,为边添加交互效果
  4. 主题适配:建议将颜色等样式抽取为可配置项,便于主题切换

总结

LogicFlow提供了高度灵活的边自定义能力,开发者可以通过继承PolylineEdgePolylineEdgeModel类,实现各种复杂的边类型。本文介绍的自定义折线边涵盖了箭头、文本、动画、样式等多个方面的定制方法,可以作为复杂边开发的参考模板。

在实际项目中,建议根据业务需求选择合适的定制粒度,平衡功能丰富性和性能表现。通过合理的属性设计,可以创建出既美观又实用的流程图边类型。