Skip to content

Instantly share code, notes, and snippets.

@Momijiichigo
Last active January 26, 2022 04:34
Show Gist options
  • Save Momijiichigo/1a5103595810d33234ba7507ffc121bc to your computer and use it in GitHub Desktop.
Save Momijiichigo/1a5103595810d33234ba7507ffc121bc to your computer and use it in GitHub Desktop.
Easy Easing

Easy Easing

easy to use smooth transition function with requestAnimationFrame

import { transition, easeInOutCubic } from './transitioner.ts'
const t = transition({
from: 0,
to: 20,
easing: easeInOutCubic,
duration: 10000,
listener(value){
console.log('*'.repeat(value))
}
})
let animFrameID: number
const render = (timestamp) =>{
// blahblahblah
if(!t.started) t.start(timestamp)
if(!t.done) t.step(timestamp)
animFrameID = requestAnimationFrame(render)
}
animFrameID = requestAnimationFrame(render)
setTimeout(()=>clearInterval(animFrameID), 15000)
/**
* 0 < x < 1
*
* 0 < output < 1
*/
type EasingFunction = (x: number) => number
// see https://easings.net/ for more easing functions
export const easeInOutCubic: EasingFunction = x => {
return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2;
}
export const transition = ({ from, to, easing, duration, listener }: {
from: number
to: number
easing: EasingFunction
duration: number
listener: (value: number) => void
}) => {
const dValue = to - from
let beginTime: number
const result = {
done: false,
started: false,
start: (timestamp: number) => {
if(result.started) return null
beginTime = timestamp
result.started = true
},
step: (timestamp: number) => {
if(!result.started) return null
const progress = (timestamp - beginTime) / duration
if (progress > 1) {
result.done = true
return null
}
listener(from + dValue * easing(progress))
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment