UNPKG

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