Elasticity With Trails
let pointX = pointY = 0;
document.addEventListener('touchmove',
e => e.preventDefault(), { passive: false });
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',
borderRadius: `${size}px`,
left: 0, top: 0
});
let x = vx = y = vy = 0;
const FADE_TIME = 800;
const plotDot = (x, y) => {
const dot = document.body.appendChild(el.cloneNode());
const time =
dot.style.transform += ' scale(.25)';
dot.style.transition = `opacity ${FADE_TIME}ms ease-out`;
window.requestAnimationFrame(() => {
dot.style.opacity = 0;
setTimeout(() => dot.parentNode.removeChild(dot), FADE_TIME);
})
}
let ticks = 0;
const loop = () => {
vx = ((pointX - x) * .08 + vx) * .95;
vy = ((pointY - y) * .08 + vy) * .95;
x += vx;
y += vy;
if (ticks++ % 2 === 0 &&
Math.abs(pointX - x) > 1 &&
Math.abs(pointY - y) > 1) {
plotDot();
}
el.style.transform = `translate(${x - halfSize}px, ${y - halfSize}px)`;
requestAnimationFrame(loop);
}
loop();
const info = document.body.appendChild(
document.createElement`div`
);
info.innerHTML = 'move mouse or finger left/right/up/down';
This is a variation on yesterdays post. This has elasticity on both axis and draws a trail of dots…