Skip to content

Instantly share code, notes, and snippets.

@Westixy
Last active August 15, 2018 04:40
Show Gist options
  • Save Westixy/8585d244b9dda50d65c99c38d182e3b2 to your computer and use it in GitHub Desktop.
Save Westixy/8585d244b9dda50d65c99c38d182e3b2 to your computer and use it in GitHub Desktop.
circularTime
export default class CircularWaiter {
_canvas: any
_ctx: any
_intervalHandler: any
_timeLeft: number
_timeTodo: number
_cs: any
weight: number
_options: any
constructor(
canvas,
{
color = 'blue',
placeholderColor = 'rgba(0,0,0,.2)',
weight = 2,
interval = 50,
} = {}
) {
this._canvas = canvas
this._ctx = canvas.getContext('2d')
this._intervalHandler = null
this._timeLeft = 0
this._timeTodo = 1
this._options = { color, placeholderColor, weight, interval }
this._updateValues()
}
_updateValues() {
this._cs = {
width: this._canvas.width,
height: this._canvas.height,
center: {
x: this._canvas.width / 2,
y: this._canvas.height / 2,
},
radius:
Math.min(this._canvas.width, this._canvas.height) / 2 -
this._options.weight / 2,
}
}
timeIt(seconds: number, autoInterval = true) {
this._clearInterval()
this._timeLeft = seconds
this._timeTodo = seconds > 0 ? seconds : 1
this._draw(0)
let interval: number = this._options.interval
if (autoInterval === true) {
// define interval from seconds (betwwen 30ms and 1s)
interval = Math.min(Math.max(10 * seconds, 30), 1000)
}
this._intervalHandler = setInterval(() => {
this._timeLeft -= interval / 1000
if (this._timeLeft < 0) {
this._draw(1)
} else this._draw(1 - this._timeLeft / this._timeTodo)
}, interval)
}
_clearInterval() {
clearInterval(this._intervalHandler)
this._intervalHandler = null
}
_draw(percent) {
this._clearCanvas()
this._drawCircle({
color: this._options.placeholderColor,
weight: this._options.weight,
})
this._drawCircle({
color: this._options.color,
weight: this._options.weight,
percent,
})
}
_drawCircle({ percent = 1, color = 'blue', weight = 2 } = {}) {
this._ctx.beginPath()
this._ctx.arc(
this._cs.center.x,
this._cs.center.y,
this._cs.radius,
-0.5 * Math.PI,
2 * Math.PI * percent - 0.5 * Math.PI,
false
)
this._ctx.lineWidth = weight
this._ctx.strokeStyle = color
this._ctx.stroke()
}
_clearCanvas() {
this._ctx.clearRect(0, 0, this._cs.width, this._cs.height)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment