Circle.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. /**
  2. * 双环形图
  3. *
  4. * @author hanyaolong
  5. */
  6. export class SCircle {
  7. /**
  8. * 构造函数
  9. *
  10. * @param {canvasid} id
  11. */
  12. constructor(id) {
  13. const canvas = document.getElementById(id);
  14. this.ctx = canvas.getContext("2d");
  15. this.percent = 100; //最终百分比
  16. this.circleX = canvas.width / 2; //中心x坐标
  17. this.circleY = canvas.height / 2; //中心y坐标
  18. this.radius = 60; //圆环半径
  19. this.lineWidth = 5; //圆形线条的宽度
  20. this.fontSize = 40; //字体大小
  21. }
  22. /**
  23. * 绘制圆
  24. *
  25. * @param {x} cx
  26. * @param {y} cy
  27. * @param {半径} r
  28. */
  29. circle(cx, cy, r) {
  30. this.ctx.beginPath();
  31. this.ctx.lineWidth = this.lineWidth;
  32. this.ctx.strokeStyle = '#2a4886';
  33. this.ctx.arc(cx, cy, r, 0, (Math.PI * 2), true);
  34. this.ctx.stroke();
  35. }
  36. /**
  37. * 设置中心文字
  38. *
  39. * @param {文本} text
  40. */
  41. setText(text) {
  42. this.ctx.beginPath();
  43. //中间的字
  44. this.ctx.font = this.fontSize + 'px April';
  45. this.ctx.textAlign = 'center';
  46. this.ctx.textBaseline = 'middle';
  47. this.ctx.fillStyle = '#ffffff';
  48. this.ctx.fillText(text, this.circleX, this.circleY);
  49. this.ctx.stroke();
  50. this.ctx.beginPath()
  51. this.ctx.font = this.fontSize / 3 + 'px April';
  52. this.ctx.textAlign = 'center';
  53. this.ctx.textBaseline = 'middle';
  54. this.ctx.fillStyle = '#ffffff';
  55. this.ctx.fillText("本月总任务", this.circleX, this.circleY + this.fontSize * 3 / 4);
  56. this.ctx.stroke();
  57. }
  58. /**
  59. * 绘制圆弧
  60. *
  61. * @param {x} cx
  62. * @param {y} cy
  63. * @param {半径} r
  64. */
  65. sector(cx, cy, r,endAngle) {
  66. this.ctx.beginPath();
  67. this.ctx.lineWidth = this.lineWidth;
  68. this.ctx.strokeStyle = '#c81d39';
  69. //圆弧两端的样式
  70. this.ctx.lineCap = 'round';
  71. this.ctx.arc(
  72. cx, cy, r,
  73. (Math.PI * -1 / 2),
  74. (Math.PI * -1 / 2) + endAngle / 100 * (Math.PI * 2),
  75. false
  76. );
  77. this.ctx.stroke();
  78. }
  79. /**
  80. * 初始化
  81. *
  82. * @param {x} x
  83. * @param {y} y
  84. * @param {半径} r
  85. */
  86. init(x, y, r) {
  87. //清除canvas内容
  88. this.ctx.clearRect(0, 0, x * 2, y * 2);
  89. this.circle(x, y, r);
  90. this.circle(x, y, r * 1.2);
  91. }
  92. /**
  93. * 设置百分比
  94. *
  95. * @param {内环百分比(100最大)} p1
  96. * @param {外环百分比(100最大)} p2
  97. */
  98. setPersent(p1, p2) {
  99. this.init(this.circleX, this.circleY, this.radius);
  100. //圆弧
  101. this.sector(this.circleX, this.circleY, this.radius, p1);
  102. this.sector(this.circleX, this.circleY, this.radius * 1.2,p2);
  103. }
  104. }