Wobbling Ball with SVG
const el = document.body.appendChild(
document.createElement('div'));
el.innerHTML = `
<svg width="100%" height="100%">
<circle
id="circ"
cx="0" cy="0" r="50"
fill="red" style="will-change: transform;"/>
</svg>
<style>
svg, div, body, html {
overflow: visible;
height: 100%;
width: 100%;
margin: 0; padding: 0;
}
</style>
`;
let w = window.innerWidth,
h = window.innerHeight,
x = w / 2,
y = h / 2,
vx = vy = dx = dy = 0,
damp = 0.99, div = 8, ticks = 0,
wobbleChance = 0.03,
startTick = 50;
function loop() {
w = window.innerWidth;
h = window.innerHeight;
if (x > w){
vx *= -1;
dx *= -1;
x = w;
} else if (x < 0){
vx *= -1;
dx *= -1;
x = 0;
}
if (y > h) {
vy *= -1;
dy *= -1;
y = h;
} else if (y < 0) {
vy *= -1;
dy *= -1;
y = 0
}
if (
Math.random() < wobbleChance ||
ticks === startTick) {
dx += Math.random() * 10 - 5;
dy += Math.random() * 10 - 5;
}
dx *= damp;
dy *= damp;
vx += (dx - vx) / div;
vy += (dy - vy) / div;
x += vx;
y += vy;
circ.setAttribute('transform', `translate(${x} ${y})`);
ticks++;
window.requestAnimationFrame(loop);
}
loop();
function resize() {
const radius = Math.min(w, h) * .05;
// `window.circ` is the global id (⌐■_■)
circ.r.baseVal.value = radius;
}
resize();
window.addEventListener('resize', resize);
A wobbling ball with svg.