Skip to content

Instantly share code, notes, and snippets.

@s-shin
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save s-shin/9071179 to your computer and use it in GitHub Desktop.

Select an option

Save s-shin/9071179 to your computer and use it in GitHub Desktop.
Small Animation Utility for CoffeeScript (JavaScript)
###
animator.coffee
(C) 2014 Shintaro Seki <[email protected]>
The MIT License
###
#
# Usage:
# fps = 15
# animator = new Animator fps, (frameCount) ->
# console.log frameCount
# animator.stop() if frameCount > fps
# .run()
#
# References:
# * http://yomotsu.net/blog/2013/01/05/fps.html
#
class Animator
requestAnimationFrame = do ->
window.requestAnimationFrame or
window.webkitRequestAnimationFrame or
window.mozRequestAnimationFrame or
window.oRequestAnimationFrame or
window.msRequestAnimationFrame or
(cb) -> window.setTimeout cb, 1000.0 / 60.0
now = window.performance and
performance.now or
performance.mozNow or
performance.msNow or
performance.oNow or
performance.webkitNow
getTime = ->
now?.call(performance) or Date.now?() or new Date().getTime()
constructor: (@fps, @fn) -> @isRunning = false
run: ->
return if @isRunning
@isRunning = true
frameTime = 1000.0 / @fps
startTime = getTime()
frameCount = 0
do loopFn = =>
requestAnimationFrame loopFn if @isRunning
currentFrameCount = Math.floor((getTime()-startTime) / frameTime)
if currentFrameCount > frameCount
frameCount = currentFrameCount
@fn frameCount
@
stop: -> @isRunning = false; @
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment