当前位置: 首页 > Web前端 > JavaScript

svg实现react-rax圆环倒计时进度条组件代码片段

时间:2023-03-27 14:55:39 JavaScript

:没有svg,几乎都需要有额外的元素遮挡才能实现,但是没有办法实现半透明的圆环效果。纯svg绘图,加宽路径的笔画宽度,视觉上呈现环状。(高中学过的三角函数你都忘记了吗?)以半径为32的圆为例。注意画笔定位基准落在中心,需要调整viewbox的大小,避免圆显示不全。(选贝自用)import{createElement,useState,useEffect,useRef,useCallback}from'rax';interfaceIProps{time:number;//毫秒样式?:Rax.CSSProperties;onEnd?:()=>void;}exportconstCircleTimer=(props:IProps)=>{constcurT=useRef(0);consttimer=useRef();const[point,setPoint]=useState('320');useEffect(()=>{return()=>{if(timer.current){clearTimeout(timer.current);}};},[]);constcalPoint=useCallback(()=>{if(curT.current>=props.time){props.onEnd&&props.onEnd();return;}timer.current=setTimeout(()=>{curT.current+=50;constdeg=(curT.current/props.time)*Math.PI*2;constx=32+32*Math.sin(deg);consty=32-32*Math.cos(deg);if(curT.current<(1/2)*props.time){setPoint(`${x}${y}`);}elseif(curT.current>(1/2)*props.time){setPoint(`3264A3232001${x}${y}`);}calPoint();},50);},[props.time,props.onEnd]);useEffect(()=>{calPoint();},[calPoint]);返回();};备注:strokewidth不生效:怀疑stroke-Width写成strokeWidth。圆环的半径不影响实际大小,但要注意根据自己的圆环半径调整viewbox的大小,避免显示不完整。本例中圆环半径为32,圆环的起点坐标和终点坐标相同,所以在使用路径法绘制时,必须设置路径的中点。在本例中,180度位置设置为中点。