Last active
November 1, 2020 22:10
-
-
Save shashfrankenstien/189ab7d4336702eb90758da74eb136c3 to your computer and use it in GitHub Desktop.
A simple arc style progress guage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function radians(degree) { | |
return (180+degree)*(Math.PI/180) | |
} | |
class ProgressArc { | |
constructor(parentSelector, size, title, maxVal){ | |
this.parent = parentSelector | |
this.w = size *3 | |
this.h = size *3 | |
if (maxVal===undefined) maxVal=100 | |
this.config = { | |
'title':title, | |
'x': this.w/2, | |
'y': this.h/2, | |
'thickness':this.h/40, | |
'radius':this.h*3/7, | |
'bg':"#d6d6d6", | |
'fg': "blue", | |
'depth':50, | |
'maxVal':maxVal, | |
} | |
this.canvas = document.createElement('canvas') | |
this.canvas.width = this.w | |
this.canvas.height = this.h | |
this.canvas.style.width = this.w/3+'px' | |
this.canvas.style.height = this.h/3+'px' | |
var parElem = document.querySelector(this.parent) | |
parElem.innerHTML = "" | |
this.canvas.id = parElem.id+"-canvas" | |
parElem.appendChild(this.canvas) | |
this.createContext() | |
} | |
createContext() { | |
var ctx = this.canvas.getContext('2d') | |
ctx.clearRect(0,0,this.w,this.h) | |
ctx.lineWidth=this.config.thickness; | |
// ctx.arc(x, y, radius, startAngle, endAngle [, anticlockwise]); | |
ctx.beginPath() | |
ctx.strokeStyle = this.config.bg | |
ctx.arc(this.config.x, this.config.y, this.config.radius, this.scale(0), this.scale(this.config.maxVal)) | |
ctx.stroke() | |
ctx.closePath() | |
if (this.config.title!==undefined) { | |
ctx.font = this.h/12+'px sans-serif' | |
var textX = this.config.x-(ctx.measureText(this.config.title).width/2) | |
var textY = this.config.y + this.h/4 | |
ctx.fillText(this.config.title, textX, textY, this.w) | |
} | |
// ctx.scale(2, 2) | |
return ctx | |
} | |
scale(val) { | |
val = Math.min(this.config.maxVal, Math.max(0, val)) | |
return radians((val * (180+(2*this.config.depth)))/this.config.maxVal-this.config.depth) | |
} | |
set(val) { | |
var ctx = this.createContext() | |
ctx.beginPath() | |
ctx.strokeStyle = this.config.fg | |
ctx.arc(this.config.x, this.config.y, this.config.radius, this.scale(0), this.scale(val)) | |
ctx.stroke() | |
ctx.closePath() | |
var text = Math.round(val).toString() | |
ctx.font = this.h/5+'px sans-serif' | |
var textX = this.config.x-(ctx.measureText(text).width/2) | |
var textY = this.config.y + this.h/15 | |
ctx.fillText(text, textX, textY) | |
} | |
} | |
// // Usage: | |
// // new ProgressArc(parentSelector, size, title, maxVal) | |
// let arc = new ProgressArc('#arc-test', 300, 'Completed', 200) | |
// arc.set(10) | |
// arc.set(90) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment