实现环形进度条效果【一】

好基友扔过来一张效果图,简单分析下,一起看看如何实现它吧。

  1. 一个半环形用于表示 0 - 100%。
  2. 半环形开头有一个圆点作为修饰。
  3. 半环形两端需要呈现为圆角。

通过 div 实现

先画一个长方形。

<div class="graph"></div>
.graph {
  width: 200px;
  height: 100px;
  border: 20px solid rgb (58, 215, 217);
}

接下来把长方形转换为半环形。

.graph {
   width: 200px;
   height: 100px;
   border: 20px solid rgb (58, 215, 217);
+  border-radius: 0 0 200px 200px;
+  border-top: none;
}

给环形开头添加圆点修饰,实际等于添加到长方形的左上角。

<div class="graph">
+  <div class="dot"></div>
</div>
.graph {
+ position: relative;
  width: 200px;
  height: 100px;
  border: 20px solid rgb (58, 215, 217);
  border-radius: 0 0 200px 200px;
  border-top: none;
}

+.dot {
+  position: absolute;
+  top: 5px;
+  left: -15px;
+  z-index: 9999;
+  width: 12px;
+  height: 12px;
+  border-radius: 50%;
+  background-color: #fff;
+  transform-origin: center top;
+}


环形有了,如何实现进度条效果呢?让半环形旋转,并隐藏超出部分。可以给元素添加 transform 使其旋转。

.graph {
  position: relative;
  width: 200px;
  height: 100px;
  border: 20px solid rgb (58, 215, 217);
  border-radius: 0 0 200px 200px;
  border-top: none;
+ transform: rotate (150deg);
}

半环形并没有根据中心点旋转,通过 transform-origin: center top 设置原点为中间顶部,即环形的中心。

.graph {
  position: relative;
  width: 200px;
  height: 100px;
  border: 20px solid rgb (58, 215, 217);
  border-radius: 0 0 200px 200px;
  border-top: none;
+ transform-origin: center top;
  transform: rotate (150deg);
}

给环形添加一个父元素,并设置超出部分隐藏。

<div class="graph-wrapper">
  <div class="graph">
    <div class="dot"></div>
  </div>
</div>
.graph-wrapper {
  width: 200px;
  height: 100px;
  overflow: hidden;
  transform: rotate (90deg);
}

动态设置环形元素的 rotate 角度实就可以实现进度条效果了。0 - 100% 对应 180 - 360deg。

可以通过 JavaScript 设置半环形的进度。

function calculateValue(range, percentage) {
  const  [start, end] = range
  const result = start + (end - start) * percentage / 100;
  return result;
}

function renderGraph(percentage) {
  const deg = calculateValue ([180, 360], percentage);
  const el = document.querySelector ('.graph')
  el.style.transform = `rotate (${deg}deg)`
}

renderGraph (30) // 30%

总结

我们先使用 div 画了一个长方形,添加 borderborder-radius 属性使其转换为半环形,又通过 transform 属性使半环形可以旋转。接下来给半环形套了一层元素,超出部分隐藏,以实现进度条效果。

在博文开头处,我们对效果图进行了分析。其中,第 3 点 “半环形两端需要呈现为圆角” 还没有被支持。限于篇幅,将在接下来的博文中实现,最终效果如下图。

posted @ 2023-11-26 15:19  guangzan  阅读(609)  评论(1编辑  收藏  举报