interpolation example
interpolation example
by Ibrahim Tanyalcin
HTML
<button>Run Animation</button>
<input type="radio" id="identity" value="identity">
<label for="identity">linear</label><br>
<input type="radio" id="elastic" value="elastic">
<label for="elastic">elastic</label><br>
<input type="radio" id="cubic" value="cubic">
<label for="cubic">cubic</label>
<div></div>
CSS
div {
width: 50px;
height: 50px;
background: green;
}
button {
margin-bottom: 10px;
}
JavaScript
let interpolators = {
identity: function(t){
t = Math.max(0,Math.min(1,t));
return t;
},
cubic: function(t){
t = Math.max(0,Math.min(1,t));
if(2*t<<0){
return 4*(t-1)*(t-1)*(t-1)+1;
} else {
return 4*t*t*t;
}
},
elastic: function(t){
t = Math.max(0,Math.min(1,t));
var range = 10.5*Math.PI;
return (range - Math.sin(range*t)/t)/(range - 1);
}
};
let selected = "identity";
const radios = Array.from(document.getElementsByTagName("input"));
radios.forEach(d => d.addEventListener("click", function(){
radios.forEach(d => d.checked = false);
this.checked = true;
selected = this.value;
}));
const lerp = (start, end, speed) => start + (end - start) * speed
const div = document.querySelector('div')
const btn = document.querySelector('button')
let pos = 0
let startTime = 0
const duration = 2000
let aF = null
const animate = () => {
const elapsed = Date.now() - startTime
const t = interpolators[selected](elapsed / duration);
if(elapsed < duration) {
pos = lerp(0, 300, t)
aF = requestAnimationFrame(animate)
} else {
cancelAnimationFrame(aF)
aF = null
pos = 300
}
console.log(pos, 300 * t)
div.style.transform = `translateX(${pos}px)`
}
btn.addEventListener('click', () => {
pos = 0
startTime = Date.now()
aF = requestAnimationFrame(animate)
})