要帮助同事写一个弧度的进度条,进度条顶部有一个小圆,具体如下
需要指出的是,我们canvas的绘制是需要弧度,所以我们代码中使用角度,等待绘制的时候再砖话为弧度值
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><div><input type="range" id="cowbell" name="cowbell" min="0" max="100" value="50" step="1"><label for="cowbell">拖拽角度变化</label></div><canvas id="canvas"></canvas><script>const cowbell = document.getElementById("cowbell");cowbell.addEventListener("input", (a, c) => {console.log(cowbell.value)draw(cowbell.value)});let canvas = document.getElementById('canvas');let ctx = canvas.getContext('2d');canvas.width = 500;canvas.height = 500;let conterw = canvas.width / 2;//弧度的中心坐标let conterh = canvas.height / 2;//弧度的中心坐标let sAngle = 150;//其实角度let eAngle = 390;//结束角度let nAngle = 100;//以sAngle为基准的角度let leng = 100;//半径draw(50)//绘制百分比进度function draw(percentage) {//清空画布ctx.clearRect(0, 0, canvas.width, canvas.height);//结束角度 - 起始角度 = 中间区域的范围值 //中间区域的范围值 / 100 *当前进度百分比//得到百分比下的角度值nAngle = (eAngle - sAngle) / 100 * percentage;//绘制一个弧度进度条底色drawArc(sAngle, eAngle, eAngle, conterw, conterh, '#e1e8ee')//绘制一个弧度有进度的drawArc(sAngle, eAngle, nAngle, conterw, conterh, '#6f78cc')//绘制圆的坐标let { x, y } = getArcFillXY(sAngle, eAngle, leng, conterw, conterh, nAngle)//绘制圆drawArcFill(x, y);}console.log()//绘制弧度function drawArc(sAngle, eAngle, nAngle, conterw, conterh, strokeStyle = '#e1e8ee') {ctx.beginPath();//在基础sAngle上加上差量的角度 nAngle += sAngle;//控制最小的角度if (sAngle > nAngle) {nAngle = sAngle;}// 控制最大的角度if (eAngle < nAngle) {nAngle = eAngle;}//绘制角度ctx.arc(conterw, conterh, leng, rad(sAngle), rad(nAngle), false);ctx.strokeStyle = strokeStyle;ctx.lineWidth = 5;ctx.stroke();ctx.closePath();}function drawArcFill(x, y) {//绘制一个半径为5得红色圆形ctx.beginPath();ctx.arc(x, y, 5, 0, 2 * Math.PI, false);ctx.fillStyle = 'red';ctx.fill();ctx.closePath();}//将上述的圆形放在进度条的头部,随着弧形的角度一起变化 /*** */function getArcFillXY(sAngle, eAngle, leng, conterw, conterh, nAngle) {//半径是let x = conterw - leng;let y = conterh;//在基础sAngle上加上差量的角度nAngle += sAngle//控制最小的角度if (sAngle > nAngle) {nAngle = sAngle;}// 控制最大的角度if (eAngle < nAngle) {nAngle = eAngle;}//差值角度let cAngle = nAngle - sAngle;x = Math.cos(rad(nAngle)) * leng + conterw;y = Math.sin(rad(nAngle)) * leng + conterh;return {x, y}}//度数转化为弧度得方法function rad(sAngle) {return sAngle * Math.PI / 180;}</script>
</body></html>