当前位置:首页 > JavaScript

js怎么实现圆环

2026-01-30 22:05:55JavaScript

使用 SVG 实现圆环

SVG 是一种矢量图形格式,可以通过 <circle><path> 标签绘制圆环。以下是一个简单的示例:

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="none" stroke="blue" stroke-width="10" />
</svg>
  • cxcy 定义圆心坐标。
  • r 定义半径。
  • fill 设置为 none 避免填充。
  • strokestroke-width 控制圆环颜色和宽度。

使用 Canvas 绘制圆环

Canvas 通过 arc 方法绘制圆环,结合 lineWidthstroke 实现效果:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.arc(50, 50, 40, 0, 2 * Math.PI);
ctx.lineWidth = 10;
ctx.strokeStyle = 'blue';
ctx.stroke();
  • arc 参数依次为圆心坐标、半径、起始角度(0)、结束角度(2π)。
  • lineWidth 控制圆环粗细,strokeStyle 设置颜色。

使用 CSS 实现圆环

通过 CSS 的 borderborder-radius 可以模拟圆环效果:

js怎么实现圆环

<div class="ring"></div>

<style>
  .ring {
    width: 80px;
    height: 80px;
    border: 10px solid blue;
    border-radius: 50%;
    background: none;
  }
</style>
  • border-radius: 50% 将元素变为圆形。
  • border 定义圆环的宽度和颜色,background 设为透明。

动态圆环(进度条效果)

结合 Canvas 或 SVG 实现动态圆环,例如进度条:

Canvas 动态示例:

js怎么实现圆环

function drawProgress(percent) {
  const ctx = document.getElementById('canvas').getContext('2d');
  ctx.clearRect(0, 0, 100, 100);
  ctx.beginPath();
  ctx.arc(50, 50, 40, -Math.PI/2, (-Math.PI/2) + (percent / 100) * 2 * Math.PI);
  ctx.lineWidth = 10;
  ctx.strokeStyle = 'green';
  ctx.stroke();
}

drawProgress(75); // 绘制75%的圆环
  • 通过调整 arc 的结束角度实现进度效果。

SVG 动态示例:

<svg width="100" height="100">
  <path d="M50,10 A40,40 0 1 1 50,90 A40,40 0 1 1 50,10" 
        fill="none" stroke="red" stroke-width="10" 
        stroke-dasharray="251.2" stroke-dashoffset="62.8" />
</svg>
  • stroke-dasharray 设置为圆周长(2πr),stroke-dashoffset 控制进度(此处为75%)。

使用第三方库

库如 D3.js 或 Chart.js 可快速实现复杂圆环:

D3.js 示例:

const svg = d3.select("body").append("svg")
  .attr("width", 100)
  .attr("height", 100);

svg.append("circle")
  .attr("cx", 50)
  .attr("cy", 50)
  .attr("r", 40)
  .attr("fill", "none")
  .attr("stroke", "purple")
  .attr("stroke-width", 8);

以上方法覆盖了从基础到进阶的圆环实现,可根据需求选择合适方案。

标签: 圆环js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现分页

js实现分页

分页的基本实现思路 在JavaScript中实现分页功能通常需要结合前端和后端逻辑。前端负责渲染分页控件和处理用户交互,后端负责提供分页数据。 前端分页实现 纯前端分页适用于数据量较小的情况,可以…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-contain…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在H…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…