progress.js 2.2 KB

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