progress.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. 'use strict';
  2. /**
  3. * Expose `Progress`.
  4. */
  5. module.exports = Progress;
  6. /**
  7. * Initialize a new `Progress` indicator.
  8. */
  9. function Progress() {
  10. this.percent = 0;
  11. this.size(0);
  12. this.fontSize(11);
  13. this.font('helvetica, arial, sans-serif');
  14. }
  15. /**
  16. * Set progress size to `size`.
  17. *
  18. * @public
  19. * @param {number} size
  20. * @return {Progress} Progress instance.
  21. */
  22. Progress.prototype.size = function(size) {
  23. this._size = size;
  24. return this;
  25. };
  26. /**
  27. * Set text to `text`.
  28. *
  29. * @public
  30. * @param {string} text
  31. * @return {Progress} Progress instance.
  32. */
  33. Progress.prototype.text = function(text) {
  34. this._text = text;
  35. return this;
  36. };
  37. /**
  38. * Set font size to `size`.
  39. *
  40. * @public
  41. * @param {number} size
  42. * @return {Progress} Progress instance.
  43. */
  44. Progress.prototype.fontSize = function(size) {
  45. this._fontSize = size;
  46. return this;
  47. };
  48. /**
  49. * Set font to `family`.
  50. *
  51. * @param {string} family
  52. * @return {Progress} Progress instance.
  53. */
  54. Progress.prototype.font = function(family) {
  55. this._font = family;
  56. return this;
  57. };
  58. /**
  59. * Update percentage to `n`.
  60. *
  61. * @param {number} n
  62. * @return {Progress} Progress instance.
  63. */
  64. Progress.prototype.update = function(n) {
  65. this.percent = n;
  66. return this;
  67. };
  68. /**
  69. * Draw on `ctx`.
  70. *
  71. * @param {CanvasRenderingContext2d} ctx
  72. * @return {Progress} Progress instance.
  73. */
  74. Progress.prototype.draw = function(ctx) {
  75. try {
  76. var percent = Math.min(this.percent, 100);
  77. var size = this._size;
  78. var half = size / 2;
  79. var x = half;
  80. var y = half;
  81. var rad = half - 1;
  82. var fontSize = this._fontSize;
  83. ctx.font = fontSize + 'px ' + this._font;
  84. var angle = Math.PI * 2 * (percent / 100);
  85. ctx.clearRect(0, 0, size, size);
  86. // outer circle
  87. ctx.strokeStyle = '#9f9f9f';
  88. ctx.beginPath();
  89. ctx.arc(x, y, rad, 0, angle, false);
  90. ctx.stroke();
  91. // inner circle
  92. ctx.strokeStyle = '#eee';
  93. ctx.beginPath();
  94. ctx.arc(x, y, rad - 1, 0, angle, true);
  95. ctx.stroke();
  96. // text
  97. var text = this._text || (percent | 0) + '%';
  98. var w = ctx.measureText(text).width;
  99. ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);
  100. } catch (ignore) {
  101. // don't fail if we can't render progress
  102. }
  103. return this;
  104. };