progress.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 `n`.
  16. *
  17. * @param {Number} n
  18. * @return {Progress} for chaining
  19. * @api public
  20. */
  21. Progress.prototype.size = function(n){
  22. this._size = n;
  23. return this;
  24. };
  25. /**
  26. * Set text to `str`.
  27. *
  28. * @param {String} str
  29. * @return {Progress} for chaining
  30. * @api public
  31. */
  32. Progress.prototype.text = function(str){
  33. this._text = str;
  34. return this;
  35. };
  36. /**
  37. * Set font size to `n`.
  38. *
  39. * @param {Number} n
  40. * @return {Progress} for chaining
  41. * @api public
  42. */
  43. Progress.prototype.fontSize = function(n){
  44. this._fontSize = n;
  45. return this;
  46. };
  47. /**
  48. * Set font `family`.
  49. *
  50. * @param {String} family
  51. * @return {Progress} for chaining
  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} for chaining
  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} for chaining
  72. */
  73. Progress.prototype.draw = function(ctx){
  74. var percent = Math.min(this.percent, 100)
  75. , size = this._size
  76. , half = size / 2
  77. , x = half
  78. , y = half
  79. , rad = half - 1
  80. , fontSize = this._fontSize;
  81. ctx.font = fontSize + 'px ' + this._font;
  82. var angle = Math.PI * 2 * (percent / 100);
  83. ctx.clearRect(0, 0, size, size);
  84. // outer circle
  85. ctx.strokeStyle = '#9f9f9f';
  86. ctx.beginPath();
  87. ctx.arc(x, y, rad, 0, angle, false);
  88. ctx.stroke();
  89. // inner circle
  90. ctx.strokeStyle = '#eee';
  91. ctx.beginPath();
  92. ctx.arc(x, y, rad - 1, 0, angle, true);
  93. ctx.stroke();
  94. // text
  95. var text = this._text || (percent | 0) + '%'
  96. , w = ctx.measureText(text).width;
  97. ctx.fillText(
  98. text
  99. , x - w / 2 + 1
  100. , y + fontSize / 2 - 1);
  101. return this;
  102. };