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

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

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

通过 div 实现

先画一个长方形。

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

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

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

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

diff 复制代码
<div class="graph">
+  <div class="dot"></div>
</div>
diff 复制代码
.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 使其旋转。

diff 复制代码
.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 设置原点为中间顶部,即环形的中心。

diff 复制代码
.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);
}

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

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

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

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

js 复制代码
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 画了一个长方形,添加 border 与 border-radius 属性使其转换为半环形,又通过 transform 属性使半环形可以旋转。接下来给半环形套了一层元素,超出部分隐藏,以实现进度条效果。

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

相关推荐
志尊宝3 天前
Vue3 零基础每日笔记(055):组件里正确使用 store——storeToRefs 解构与 $patch 批量修改
笔记·vue·html·前端开发·软件开发
吴声子夜歌3 天前
HTML——看似普通的元素的背后(<a>标签)
html
IMPYLH3 天前
HTML 的 <style> 元素
前端·html
刃神太酷啦3 天前
前端入门第一课:HTML 基础语法 + 常用标签 + 实战全解
服务器·c语言·前端·javascript·css·c++·html
IMPYLH3 天前
HTML 的 <strong> 元素
前端·html
开开心心就好4 天前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
扶苏10024 天前
CSS 图标换色指南:用 brightness / invert / mask 把任意图片改成想要的颜色
css
我命由我123454 天前
CSS - CSS 媒体查询 orientation
前端·javascript·css·html·css3·html5·js
咩咩啃树皮4 天前
ES6 Set 核心特点 + 最简数组去重
前端·javascript·html
zhanghaha13144 天前
HTML系列教程:18_HTML / CSS 颜色零基础详解
css·html·tensorflow