Skip to content

Instantly share code, notes, and snippets.

@chrisyip
Created August 29, 2015 07:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisyip/a86afd67ffbc73c95df9 to your computer and use it in GitHub Desktop.
Save chrisyip/a86afd67ffbc73c95df9 to your computer and use it in GitHub Desktop.
SVG progress bar
class ProgressBar {
constructor (viewSize) {
this.viewSize = viewSize
this.circleStrokeColor = '#249fff'
this.circleStrokeWidth = 5
this.circleFillColor = 'transparent'
let svg = this.svg = this.createSVG()
svg.setAttribute('width', viewSize)
svg.setAttribute('height', viewSize)
let radius = viewSize / 2
let realRadius = radius * 0.9
let circle = this.circle = this.createCircle()
circle.setAttribute('r', realRadius)
circle.setAttribute('cx', radius)
circle.setAttribute('cy', radius)
circle.setAttribute('transform', `rotate(-90, ${radius}, ${radius})`)
this.dashLength = Math.PI * 2 * realRadius
circle.style.strokeDashoffset = this.dashLength
circle.style.strokeDasharray = this.dashLength
this.text = this.createText()
this.svg.appendChild(circle)
this.svg.appendChild(this.text)
this.progress = 0
}
update (progress) {
if (typeof progress === 'number' && !Number.isNaN(progress)) {
this.progress = progress
}
this.text.textContent = this.progress
let dashLength = this.dashLength
this.circle.style.strokeDashoffset = this.progress > 0 ? dashLength - dashLength * this.progress / 100 : dashLength
}
get ns () {
return 'http://www.w3.org/2000/svg'
}
createSVG () {
let svg = document.createElementNS(this.ns, 'svg')
svg.setAttribute('viewport', '0 0 100 100')
svg.setAttribute('version', '1.1')
return svg
}
createCircle () {
let circle = document.createElementNS(this.ns, 'circle')
circle.setAttribute('fill', this.circleFillColor)
circle.setAttribute('stroke', this.circleStrokeColor)
circle.setAttribute('stroke-width', this.circleStrokeWidth)
circle.style.transition = 'all .5s linear'
return circle
}
createText () {
let text = document.createElementNS(this.ns, 'text')
text.setAttribute('x', '50%')
text.setAttribute('y', '50%')
text.setAttribute('dy', '.35em')
text.setAttribute('text-anchor', 'middle')
return text
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment