Skip to content

Instantly share code, notes, and snippets.

@jsmesami
Created March 4, 2018 11:38
Show Gist options
  • Save jsmesami/a3a2a7dcdf69e541f0f4f9d9096ab530 to your computer and use it in GitHub Desktop.
Save jsmesami/a3a2a7dcdf69e541f0f4f9d9096ab530 to your computer and use it in GitHub Desktop.
A simple ClojureScript function for linear animation
;; Function takes two numeric values, `from` and `to` you wish to animate.
;; First argument is a callback function, which is called each keyframe and the current value is passed to it.
;; There are also optional keyword arguments you can use to alter duration and number of keyframes of the animation.
;; The `then` callback can be used after the animation finishes for cleanup etc.
(defn animate
([callback from to & {:keys [duration keyframes then]
:or {duration 1000
keyframes 30}}]
(let [distance (js/Math.abs (- to from))
delta (/ distance keyframes)
current-frame (atom 0)
cursor (atom from)
shift (if (< from to) + -)
interval (atom nil)]
(reset! interval (js/setInterval (fn []
(if (< @current-frame keyframes)
(do (swap! current-frame inc)
(swap! cursor shift delta)
(callback (js/Math.round @cursor)))
(do (js/clearInterval @interval)
(when then (then)))))
(/ duration keyframes))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment