1. #cvs {
    2. width: 200px;
    3. height: 200px;
    4. }
    1. <canvas id="cvs" width="400" height="400">您的浏览器不支持canvas标签。 </canvas>
    1. /** 绘制圆形进度条
    2. * @description:
    3. * @param {*} drawing_elem 绘制对象
    4. * @param {*} percent 绘制圆环百分比, 范围[0, 100]
    5. * @param {*} forecolor 绘制圆环的前景色,颜色代码
    6. * @param {*} bgcolor 绘制圆环的背景色,颜色代码
    7. * @return {*}
    8. */
    9. function drawMain(drawing_elem, percent, forecolor, bgcolor) {
    10. var context = drawing_elem.getContext("2d");
    11. var center_x = drawing_elem.width / 2;
    12. var center_y = drawing_elem.height / 2;
    13. var rad = Math.PI * 2 / 100;
    14. var speed = 0;
    15. // 绘制背景圆圈
    16. function backgroundCircle() {
    17. context.save();
    18. context.beginPath();
    19. context.lineWidth = 30; //设置线宽
    20. var radius = center_x - context.lineWidth;
    21. context.lineCap = "round";
    22. context.strokeStyle = bgcolor;
    23. context.arc(center_x, center_y, radius, 0, Math.PI * 2, false);
    24. context.stroke();
    25. context.closePath();
    26. context.restore();
    27. }
    28. //绘制运动圆环
    29. function foregroundCircle(n) {
    30. context.save();
    31. context.strokeStyle = forecolor;
    32. context.lineWidth = 30;
    33. context.lineCap = "round";
    34. var radius = center_x - context.lineWidth;
    35. context.beginPath();
    36. context.arc(center_x, center_y, radius, -Math.PI / 2, -Math.PI / 2 + n * rad, false); //用于绘制圆弧context.arc(x坐标,y坐标,半径,起始角度,终止角度,顺时针/逆时针)
    37. context.stroke();
    38. context.closePath();
    39. context.restore();
    40. }
    41. //绘制文字
    42. function text(n) {
    43. context.save(); //save和restore可以保证样式属性只运用于该段canvas元素
    44. context.fillStyle = "gray";
    45. var font_size = 50;
    46. context.font = font_size + "px Helvetica";
    47. var text_width = context.measureText(n.toFixed(0) + "%").width;
    48. context.fillText(n.toFixed(0) + "%", center_x - text_width / 2, (center_y + font_size / 2) + 20);
    49. context.restore();
    50. }
    51. //执行动画
    52. (function drawFrame() {
    53. window.requestAnimationFrame(drawFrame);
    54. context.clearRect(0, 0, drawing_elem.width, drawing_elem.height);
    55. backgroundCircle();
    56. text(speed);
    57. foregroundCircle(speed);
    58. if (speed >= percent) return;
    59. speed += 1;
    60. }());
    61. }
    62. drawMain(document.getElementById("cvs"), 100, "#07c160", "#BDBDBD")