效果图:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Canvas</title> 9 <style> 10 canvas { 11 margin: 0 auto; 12 border: 1px solid #aaa; 13 display: block; 14 } 15 </style> 16 </head> 17 18 <body> 19 <canvas width="500px" height="500px" id="canvas"></canvas> 20 21 <script> 22 var canvas = document.querySelector("#canvas"); 23 var ctx = canvas.getContext("2d"); 24 var w = canvas.width; 25 var h = canvas.height; 26 27 ctx.lineWidth = 3; 28 ctx.font = "50px 微软雅黑"; 29 ctx.textAlign = "center"; 30 ctx.textBaseline = "middle"; 31 32 var deg = Math.PI * 2 / 100; 33 var count = 0; 34 var color = "rgb(" + parseInt(Math.random() * 255) + 35 "," + parseInt(Math.random() * 255) + 36 "," + parseInt(Math.random() * 255) + ")"; 37 38 // 画圆 39 function drawCricle(x, y, r, startDeg, endDeg, lineWidth, color) { 40 ctx.beginPath(); 41 ctx.arc(x, y, r, startDeg, endDeg); 42 ctx.strokeStyle = color || "#000"; 43 ctx.lineWidth = lineWidth; 44 ctx.stroke(); 45 } 46 47 // 圆心文字 48 function drawText() { 49 ctx.fillStyle = color; 50 ctx.fillText(count.toString() + "%", w / 2, h / 2); 51 } 52 53 // main 54 function animation(color) { 55 ctx.clearRect(0, 0, w, h); 56 drawCricle(w / 2, h / 2, 200, 0, Math.PI * 2, 2, "#eee"); 57 drawCricle(w / 2, h / 2, 200, -Math.PI / 2, -Math.PI / 2 + count * deg, 5, color); 58 drawText(); 59 } 60 61 function loop() { 62 count++; 63 window.requestAnimationFrame(loop); 64 if (count > 100) { 65 count = 0; 66 color = "rgb(" + parseInt(Math.random() * 255) + 67 "," + parseInt(Math.random() * 255) + 68 "," + parseInt(Math.random() * 255) + ")"; 69 } 70 animation(color); 71 } 72 73 loop(); 74 </script> 75 </body> 76 77 </html>