UV指数指示器优化:圆形与弧渐变一致及过渡动画实现
UV指数指示器优化方案
一、让圆形匹配弧形的渐变颜色
弧形采用绿→黄→红的线性渐变,我们可以根据UV指数的百分比,通过RGB颜色插值计算出圆形对应的渐变颜色:
- 当UV指数百分比在0-0.5区间时,实现绿色(#4CAF50)到黄色(#FFEB3B)的过渡
- 当百分比在0.5-1区间时,实现黄色到红色(#F44336)的过渡
二、实现圆形的过渡动画
给圆形元素添加CSS过渡属性,修改坐标和颜色时会自动触发平滑动画,这种方式简洁高效,无需复杂的JS动画逻辑。
以下是修改后的完整代码:
HTML 部分
<div style="height: 300px; width: 300px; margin: 100px"> <svg viewBox="0 0 100 50" style="height: 80%; width: 50%; transform: rotate(90deg)"> <defs> <linearGradient id="color-gradient"> <stop offset="0%" stop-color="#4CAF50" /> <stop offset="50%" stop-color="#FFEB3B" /> <stop offset="100%" stop-color="#F44336" /> </linearGradient> </defs> <path d="M 10 50 A 40 40 0 0 1 90 50" stroke-width="5" stroke-linecap="round" fill="none" stroke="url(#color-gradient)" transform="rotate(-90,50,50)" /> <!-- 添加过渡动画样式,初始位置匹配0指数位置 --> <circle cx="50" cy="10" r="5" fill="#4CAF50" style="transition: cx 0.6s ease, cy 0.6s ease, fill 0.6s ease;" /> </svg> </div>
JS 部分
// 示例UV指数,可替换为实际业务值 let uvIndex = 7; // 限制UV指数在0-10的有效范围内 uvIndex = Math.max(0, Math.min(10, uvIndex)); const percentage = uvIndex / 10; // 计算圆形的目标坐标 const degrees = percentage * 180 + 90; const x = 50 + 40 * Math.cos((degrees * Math.PI) / 180); const y = 50 + 40 * Math.sin((degrees * Math.PI) / 180); // 根据百分比计算对应渐变颜色 function getGradientColor(percent) { let r, g, b; if (percent <= 0.5) { // 绿→黄颜色插值 const t = percent * 2; r = Math.round(76 + (255 - 76) * t); g = Math.round(175 + (235 - 175) * t); b = Math.round(80 + (59 - 80) * t); } else { // 黄→红颜色插值 const t = (percent - 0.5) * 2; r = Math.round(255 + (244 - 255) * t); g = Math.round(235 + (67 - 235) * t); b = Math.round(59 + (54 - 59) * t); } return `rgb(${r},${g},${b})`; } const circle = document.querySelector("circle"); // 设置圆形目标状态(坐标+颜色) circle.setAttribute("cx", x); circle.setAttribute("cy", y); circle.setAttribute("fill", getGradientColor(percentage));
内容的提问来源于stack exchange,提问作者Starnec
相关产品推荐
相关产品推荐

