Canvas繪制圓形進度條
canvas畫布坐標點,如下圖:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Canvas繪制圓形進度條</title> </head> <body> <h1>繪制圓形進度條</h1> <!--畫布--> <canvas style="background: #efefef;" id="canvas" width="500" height="500"></canvas> <script> var ctx = canvas.getContext('2d');//生成畫筆對象 ctx.lineWidth = 30;//線條的寬度 ctx.font = '60px SimHei';//字體樣式 var start = -90, end = -90;//起止點 var timer = setInterval(function () { ctx.clearRect(0, 0, 500, 500);//清除畫布已有內容 end += 10; //繪制圓弧 ctx.beginPath();//開始繪制路徑 ctx.arc(250, 250, 100, start * Math.PI / 180, end * Math.PI / 180);//繪制一個弧線 if (end - start < 120) { //1/3范圍內 紅色 ctx.strokeStyle = 'red';//輪廓/描邊的顏色 ctx.fillStyle = 'red';//填充顏色 } else if (end - start < 240) { ctx.strokeStyle = 'orange'; ctx.fillStyle = 'orange'; } else { ctx.strokeStyle = 'green'; ctx.fillStyle = 'green'; } ctx.stroke();//對一條路徑描邊 var percentage = Math.floor((end - start) / 360 * 100) + '%';//繪制文字 var txtWidth = ctx.measureText(percentage).width; //獲得文字的寬度 ctx.fillText(percentage, 250 - txtWidth / 2, 250 + 30); //繪制文本 if (end >= 270) { clearInterval(timer); } }, 200) </script> </body> </html>
運行效果: