Elasticity
let pointX = pointY = 0;
document.addEventListener('mousemove', e => {
pointX = e.clientX;
pointY = e.clientY;
});
document.addEventListener('touchmove', e => {
pointX = e.touches[0].clientX
pointY = e.touches[0].clientY
});
let el = document.body.appendChild(
document.createElement`div`
);
const size = 20;
const halfSize = size / 2;
Object.assign(el.style, {
position: 'absolute',
width: `${size}px`,
height: `${size}px`,
background: 'red',
left: 0, top: 0
})
let x = vx = 0;
const loop = () => {
vx = ((pointX - x) * .2 + vx) * .79;
x += vx;
el.style.transform = `translate(${x - halfSize}px, 50px)`;
requestAnimationFrame(loop);
}
loop();
let info = document.body.appendChild(
document.createElement`div`
);
info.innerHTML = 'move mouse or finger left/right';
Basic interactive elasticity with mouse or touch