生活随笔
收集整理的這篇文章主要介紹了
实现环形进度条
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
css3方式
const Circle = () => {const [step, setStep] = React.useState(0)const handleAdd = () => {let num = (step + 10) * 3.6const leftEl = document.getElementsByClassName('left')const rightEl = document.getElementsByClassName('right')if(num < 180) {rightEl[0].style.transform = 'rotate(' + num + 'deg)'} else {rightEl[0].style.transform = 'rotate(180deg)'leftEl[0].style.transform = 'rotate(' + (num-180) + 'deg)'}setStep(pre => pre + 10)}return (<div className={styles.circle}><div className="pie-right"><div className="right"></div></div><div className="pie-left"><div className="left"></div></div><div className="mask"><span>{step}</span>%</div><button onClick={handleAdd}>add 10%</button></div>)
}// scss
$width: 200px;
$half: 100px;
$mask: 150px;
$maskTop: 25px;.circle {position: absolute;height: $width;width: $width;border-radius: 50%;background: red;:global {.pie-right, .pie-left { //這倆元素主要是為了分別生成兩個半圓的,所以起作用的地方在于clip裁掉另一半position: absolute;top: 0;left: 0;height: $width;width: $width;border-radius: 50%;}.right, .left {position: absolute;top: 0;left: 0;height: $width;width: $width;border-radius: 50%;background: blue;//注意這個才不是當前進度的顏色}.pie-right, .right { //裁掉左邊一半clip: rect(0, auto, auto, $half);}.pie-left, .left { //裁掉右邊一半clip: rect(0, $half, auto, 0);}.mask {//我是遮罩 maskposition: absolute;top: $maskTop;left: $maskTop;height: $mask;width: $mask;background: #fff;border-radius: 50%;text-align: center;}}
}
canvas形式
const Progress = () => {const baseColor = '#e1e1e1',coverColor = '#fe4d43',PI = Math.PI,lineWidth = 20,sR = -PI/2, // 起始位置rad = Math.PI*2/100 //將360度分成100份,那么每一份就是rad度let cxt = React.useRef(null),percent = 0,cWidth = 0,cHeight = 0React.useEffect(() => {cWidth = cxt.current.widthcHeight = cxt.current.heightcxt = cxt.current.getContext('2d')handleUpdate()}, [])const handleUpdate = () => {// 進行動畫處理// window.requestAnimationFrame(handleUpdate) cxt.clearRect(0, 0, cWidth, cHeight)handleDraw(baseColor, cWidth/2, cHeight/2, 80, 0, 2*PI )handleDraw(coverColor, cWidth/2, cHeight/2, 80, sR, sR + percent*rad)handleText()if (percent > 100) {percent = 0}percent += 10}const handleText = () => {// 繪制數字cxt.fillStyle = coverColorcxt.font = '40px PT Sans'const textWidth = cxt.measureText(percent+'%').widthcxt.fillText(percent+'%', cWidth/2 -textWidth/2, cHeight/2 + 15)}const handleDraw = (color, x, y, r, sRadian, eRadian) => {cxt.beginPath()cxt.lineCap = 'rect'cxt.strokeStyle = colorcxt.lineWidth = lineWidthcxt.arc(x, y, r, sRadian, eRadian, false)cxt.stroke()}return (<><canvas width={200} height={200} className={styles["canvas-circle"]} ref={cxt}>wc瀏覽器不支持, 沙雕快升級你的瀏覽器吧</canvas><button onClick={handleUpdate}>加進度</button></>)
}
總結
以上是生活随笔為你收集整理的实现环形进度条的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。