progress.js 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. let Progress = function (init) {
  2. this.init(init)
  3. };
  4. Progress.prototype = {
  5. init: function (init) {
  6. this.el = init.el;//元素ID
  7. let cvsElement = document.getElementById(this.el),//获取元素
  8. ctx = cvsElement.getContext("2d"),//获取画笔
  9. width = cvsElement.width,//元素宽度
  10. height = cvsElement.height,//元素高度
  11. degActive = 0,//动态线条
  12. timer = null;//定时器
  13. //停止时的角度
  14. init.deg >= 0 && init.deg <= 100 ? this.deg = init.deg : this.deg = 100;
  15. //线宽
  16. init.lineWidth !== undefined ? this.lineWidth = init.lineWidth : this.lineWidth = 20;
  17. //判断宽高较小者
  18. this.wh = width > height ? height : width;
  19. //设置圆的半径,默认为宽高较小者
  20. init.circleRadius > 0 && init.circleRadius <= this.wh / 2 - this.lineWidth / 2 ?
  21. this.circleRadius = init.circleRadius : this.circleRadius = this.wh / 2 - this.lineWidth / 2;
  22. //绘制线的背景颜色
  23. init.lineBgColor !== undefined ?
  24. this.lineBgColor = init.lineBgColor : this.lineBgColor = '#ccc';
  25. //绘制线的颜色
  26. init.lineColor !== undefined ?
  27. this.lineColor = init.lineColor : this.lineColor = '#009ee5';
  28. //绘制文字颜色
  29. init.textColor !== undefined ?
  30. this.textColor = init.textColor : this.textColor = '#009ee5';
  31. //绘制文字大小
  32. init.fontSize !== undefined ?
  33. this.fontSize = init.fontSize : this.fontSize = parseInt(this.circleRadius / 2);
  34. //执行时间
  35. this.timer = init.timer;
  36. //清除锯齿
  37. if (window.devicePixelRatio) {
  38. cvsElement.style.width = width + "px";
  39. cvsElement.style.height = height + "px";
  40. cvsElement.height = height * window.devicePixelRatio;
  41. cvsElement.width = width * window.devicePixelRatio;
  42. ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
  43. }
  44. //设置线宽
  45. ctx.lineWidth = this.lineWidth;
  46. //启动定时器
  47. timer = setInterval(function () {
  48. ctx.clearRect(0, 0, width, height);//清除画布
  49. ctx.beginPath();//开始绘制底圆
  50. ctx.arc(width / 2, height / 2, this.circleRadius, 1, 8);
  51. ctx.strokeStyle = this.lineBgColor;
  52. ctx.stroke();
  53. ctx.beginPath();//开始绘制动态圆
  54. ctx.arc(width / 2, height / 2, this.circleRadius, -Math.PI / 2, degActive * Math.PI / 180 - Math.PI / 2);
  55. ctx.strokeStyle = this.lineColor;
  56. ctx.stroke();
  57. let txt = (parseInt(degActive * 100 / 360) + "%");//获取百分比
  58. ctx.font = this.fontSize + "px SimHei";
  59. let w = ctx.measureText(txt).width;//获取文本宽度
  60. let h = this.fontSize / 2;
  61. ctx.fillStyle = this.textColor;
  62. ctx.fillText(txt, width / 2 - w / 2, height / 2 + h / 2);
  63. if (degActive >= this.deg / 100 * 360) {//停止定时器
  64. clearInterval(timer);
  65. timer = null;
  66. }
  67. degActive++;
  68. }.bind(this), this.timer);
  69. }
  70. };