Snek/src/js/progress.js

45 lines
1,011 B
JavaScript
Raw Normal View History

2020-03-24 12:01:24 +00:00
class ProgressBar {
constructor(taskCount) {
this.taskCount=taskCount;
this.completeCount=0;
this.updateListeneres=[];
}
get percent() {
return Math.floor(this.completeCount/this.taskCount*100);
}
get ready() {
return this.completeCount==this.taskCount;
}
addUpdateListener(fn) {
this.updateListeneres.push(fn.bind(this));
}
addReadyListener(fn) {
this.updateListeneres.push(() => {
if(this.ready) fn.bind(this)();
});
}
update() {
this.completeCount++;
this.updateListeneres.forEach(l => l(this));
}
draw(canvas, bgColor='red', textColor='black') {
let ctx=canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle=bgColor;
ctx.fillRect(0, 0, canvas.width*this.completeCount/this.taskCount, canvas.height);
ctx.fillStyle=textColor;
ctx.textAlign='center';
ctx.textBaseline='center';
ctx.font=`${canvas.height/2}px 'Fira Code'`;
ctx.fillText(this.percent+'%', canvas.width/2, canvas.height/2);
}
}
return ProgressBar;