不引入第三方库,绘制圆环

在前端项目中,选择使用 第三方库 还是 简单的 CSS/JS 来实现圆环,取决于项目的需求、复杂度、开发效率以及性能要求。

适合使用第三方库的情况

  • 复杂的数据可视化需求:需要展示多组数据、动态更新数据或交互复杂的圆环图。
  • 需要丰富的图表功能:需要支持图例、工具提示、动画效果等功能。
  • 开发时间有限:项目时间紧张,需要快速实现功能。
  • 跨浏览器兼容性要求高:需要兼容多种浏览器。
  • 团队技术栈统一:团队已经熟悉某个第三方库,且项目中已经使用了该库。

推荐的第三方库:

  • ECharts:功能强大,适合复杂的数据可视化。
  • Chart.js:轻量易用,适合简单的图表需求。
  • D3.js:高度自定义,适合需要极致控制的场景。

适合使用简单的 CSS/JS 的情况

  • 简单的静态圆环
  • 性能要求高
  • 项目规模小
  • 自定义需求强

实现方式

方法 1:使用纯 CSS 实现圆环图

html 复制代码
<div class="ring">
  <div class="ring-inner"></div>
</div>
css 复制代码
.ring {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: conic-gradient(#4caf50 75%, #e0e0e0 0);
  position: relative;
}

.ring-inner {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  • 使用 conic-gradient 实现环形颜色填充,conic-gradient锥形渐变。
  • 通过内部的白色圆形遮罩实现圆环效果。

方法 2:使用 SVG 实现圆环图

arduino 复制代码
<svg width="100" height="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" stroke="#e0e0e0" stroke-width="10" fill="none" />
  <circle cx="50" cy="50" r="40" stroke="#4caf50" stroke-width="10" fill="none"
          stroke-dasharray="251.2" stroke-dashoffset="62.8" />
</svg>
  • 第一个 <circle> 绘制背景圆环。
  • 第二个 <circle> 绘制前景圆环,通过 stroke-dasharraystroke-dashoffset 控制圆环的进度。
  • stroke-dasharray 是圆环的周长(2 * π * r),stroke-dashoffset 是圆环的空白部分。

方法 3:使用 Canvas 实现圆环图

arduino 复制代码
<canvas id="ringCanvas" width="100" height="100"></canvas>
ini 复制代码
const canvas = document.getElementById('ringCanvas');
const ctx = canvas.getContext('2d');

function drawRing(progress) {
  const centerX = canvas.width / 2;
  const centerY = canvas.height / 2;
  const radius = 40;
  const lineWidth = 10;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制背景圆环
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
  ctx.strokeStyle = '#e0e0e0';
  ctx.lineWidth = lineWidth;
  ctx.stroke();

  // 绘制前景圆环
  ctx.beginPath();
  ctx.arc(centerX, centerY, radius, -Math.PI / 2, (Math.PI * 2 * progress) - Math.PI / 2);
  ctx.strokeStyle = '#4caf50';
  ctx.lineWidth = lineWidth;
  ctx.stroke();
}

// 绘制一个 75% 的圆环
drawRing(0.75);
  • 使用 ctx.arc 绘制圆环。
  • 通过 progress 参数控制圆环的进度。

ps: 如果需要实现带弧度的圆环尖端,可以使用SVG, Canvas 或者Css 和 SVG相结合。

相关推荐
Codigger官方几秒前
Linux 基金会牵头成立 React 基金会:前端开源生态迎来里程碑式变革
linux·前端·react.js
90后的晨仔2 分钟前
🌟 Vue3 + Element Plus 表格开发实战:从数据映射到 UI 优化的五大技巧
前端
ObjectX前端实验室1 小时前
【图形编辑器架构】🧠 Figma 风格智能选择工具实现原理【猜测】
前端·react.js
天桥下的卖艺者1 小时前
R语言基于shiny开发随机森林预测模型交互式 Web 应用程序(应用程序)
前端·随机森林·r语言·shiny
技术钱1 小时前
vue3 两份json数据对比不同的页面给于颜色标识
前端·vue.js·json
路很长OoO1 小时前
Flutter 插件开发实战:桥接原生 SDK
前端·flutter·harmonyos
开水好喝2 小时前
Code Coverage Part I
前端
DoraBigHead2 小时前
🧭 React 理念:让时间屈服于 UI —— 从同步到可中断的演化之路
前端·javascript·面试
敢敢J的憨憨L2 小时前
GPTL(General Purpose Timing Library)使用教程
java·服务器·前端·c++·轻量级计时工具库
喝拿铁写前端3 小时前
Vue 组件通信的两种世界观:`.sync` 与普通 `props` 到底有什么不同?
前端·vue.js·前端框架