const MPI = Math.PI;
const MPI2 = Math.PI * 2;
var dial = {
start : -MPI / 2,
min : 0,
max : 100,
value : 0,
width : 20,
innerWidth : 16,
back : "gray",
color : "#7F3",
font : "62px arial",
textCol : "gray",
ctx : null,
rendering : false,
setRenderContext : function(context){
this.ctx = context;
this.draw = this.draw.bind(this);
},
setValue : function(val){
this.value = Math.min(this.max,Math.max(this.min,val));
if(!this.rendering){
this.rendering = true;
requestAnimationFrame(this.draw);
}
},
draw : function drawDial(){
this.rendering = false;
if(this.ctx === null){
return;
}
const ctx = this.ctx;
const w = ctx.canvas.width;
const h = ctx.canvas.height;
var r = Math.min(w, h) / 2;
const cw = w / 2;
const ch = h / 2;
ctx.clearRect(0,0,w,h);
ctx.fillStyle = this.back;
ctx.beginPath();
ctx.arc(cw, ch, r, 0, MPI2);
ctx.arc(cw, ch, r - this.width, 0, MPI2, true);
ctx.fill();
var ang = (this.value - this.min) / (this.max-this.min);
var percent = (ang * 100).toFixed(0) + "%";
ang *= MPI2;
r -= this.width / 2;
r += this.innerWidth / 2;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(cw, ch, r, this.start, this.start + ang);
ctx.arc(cw, ch, r - this.innerWidth, this.start + ang, this.start, true);
ctx.fill();
if(this.font !== null){
ctx.font = this.font;
ctx.fillStyle = this.textCol;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(percent, cw, ch);
}
}
}
const canvas = document.createElement("canvas");
canvas.width = 200;
canvas.height = 200;
const ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
var myValue = 1;
dial.setRenderContext(ctx);
dial.setValue(0);
var speed = 1;
function moveDialUp(){
myValue += speed;
dial.setValue(myValue);
if(myValue > 100){
myValue = 0;
speed = Math.random() * 5 + 1;
setTimeout(moveDialUp, 2000);
}else{
setTimeout(moveDialUp, 50);
}
}
moveDialUp();