Vant Circle 环形进度条 组件分析

1,755 阅读1分钟

介绍

圆环形的进度条组件,支持进度渐变动画。

实现思路

1.技术难点

如何实现进度条?

答:通过设置<path>strokeDasharrayCSS属性,来实现。

2.具体步骤

  1. 准备一个svg画布
  2. 画一个圆,并使用白色描边 <path class="van-circle__layer">
  3. 根据当前 rate/max 渲染上层的进度圆(有颜色)<path class="van-circle__hover">
  4. 最上层,呈现 文字信息

如下图:

核心代码分析

1.组件核心render函数

export default {
  render() {
    return (
      <div class={bem()} style={this.style}>
      	// 画布
        <svg viewBox={`0 0 ${this.viewBoxSize} ${this.viewBoxSize}`}>
          // 底层 圆
          <path class={bem('hover')} style={this.hoverStyle} d={this.path} />
          // 上层的进度圆
          <path
            d={this.path}
            class={bem('layer')}
            style={this.layerStyle}
            stroke={this.gradient ? `url(#${this.uid})` : this.color}
          />
        </svg>
        // 展示文本信息
        {this.slots() ||
          (this.text && <div class={bem('text')}>{this.text}</div>)}
      </div>
    );
  },
}

2. 进度圆的样式函数

监听了rate变化,实时计算 进度条的百分比。

const PERIMETER = 3140;

layerStyle() {
  const offset = (PERIMETER * this.value) / 100;

  return {
    stroke: `${this.color}`,
    strokeWidth: `${this.strokeWidth + 1}px`,
    strokeLinecap: this.strokeLinecap,
    strokeDasharray: `${offset}px ${PERIMETER}px`,
  };
},