Open this page on your phone and give it a shake. The snow swirls up, drifts back down as if through water, and settles on the headings and buttons. Tilt the phone and the snow slides to the side.
I'm František, and I make animated effects for websites at Fluri. The Snow Globe is free on npm under MIT. Here's how it works: phone sensors, the iPhone permission tap, fake water physics and snow that lands on real text.
1. Feeling the shake
Phones report motion through the devicemotion event. accelerationIncludingGravity gives three numbers in m/s². A phone resting on a table reads about 9.8 on one axis, which is gravity.
A shake is a sudden change in those numbers, so I compare each reading with the previous one. The size of that jump is the "jerk". Above about 13 m/s² it's a real shake, not just a hand moving the phone.
let last = null; function onMotion(e) { const a = e.accelerationIncludingGravity; if (!a || a.x === null) return; if (last) { const jerk = Math.hypot(a.x - last.x, a.y - last.y, a.z - last.z); if (jerk > 13) shake(Math.min(1.8, jerk / 22)); // stronger shake, more snow } last = { x: a.x, y: a.y, z: a.z }; } A shake fires many readings in a row, so shake() ignores calls less than 220 ms apart.
2. The iPhone permission tap
On iPhone, motion events stay silent until the page asks permission, and Safari only allows that request inside a tap. Newer Chrome builds expose the same requestPermission function, so I check for the function rather than the browser.
async function enableMotion() { const DM = window.DeviceMotionEvent; if (typeof DM?.requestPermission === "function") { const answer = await DM.requestPermission(); // must run inside a tap if (answer !== "granted") return false; } addEventListener("devicemotion", onMotion); return true; } In the UI, the hint pill turns into a button that says "Tap here, then shake your phone". If someone says no, a small globe button in the corner still shakes it.
3. Which way is down?
Tilting is the part people don't expect. The snow should fall towards the real ground, not the bottom of the screen.
The spec says the reading points away from gravity, so gravity in screen terms is x = -a.x, y = a.y. iOS has historically reported these with the opposite sign, so I flip them there. Then I rotate by the screen orientation, so it still works in landscape.
const ios = /iPhone|iPad|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1); const sign = ios ? -1 : 1; let gx = -a.x * sign; let gy = a.y * sign; const r = (-(screen.orientation?.angle ?? 0) * Math.PI) / 180; [gx, gy] = [gx * Math.cos(r) - gy * Math.sin(r), gx * Math.sin(r) + gy * Math.cos(r)]; // A phone lying flat has almost no sideways gravity: let the snow sink gently. if (Math.hypot(gx, gy) < 3.5) { gx = 0; gy = 4.9; } I ease the snow's gravity towards the new direction over a few frames, so a wobbly hand doesn't make it jitter.
4. Snow that falls like it's in water
Real snow globes are full of liquid, so flakes don't accelerate. They sink at a steady speed, and bigger flakes sink faster. Instead of simulating forces, each flake eases towards a target velocity.
After a shake, an energy value adds a swirling current made of a few sine waves. Energy fades away exponentially, so the swirl calms down in about five seconds and the snow takes another twenty to settle.
const k = 1 - Math.exp(-dt * 2.4); // how quickly a flake reaches its target speed for (const f of flakes) { const terminal = (12 + f.radius * 8) * speed; // px per second let tx = gx / 9.8 * terminal; let ty = gy / 9.8 * terminal; if (energy > 0) { tx += Math.sin(f.y * 0.0075 + t * 1.3) * Math.cos(f.x * 0.0042 - t * 0.7) * 240 * energy; ty += (Math.cos(f.x * 0.0068 - t * 1.1) * Math.sin(f.y * 0.0051 + t * 0.5) - 0.25) * 240 * energy; } f.vx += (tx - f.vx) * k; f.vy += (ty - f.vy) * k; f.x += f.vx * dt; f.y += f.vy * dt; } energy *= Math.exp(-dt * 0.5); // the water calms down The - 0.25 in the vertical current lifts the snow a little, so a shake throws it upwards first, like a real globe.
5. Snow that lands on your headings
The snow piles up on h1, h2, buttons and cards. The obvious approach, getBoundingClientRect(), gives the element's box, and for a heading that box is wider than the text and taller than the letters. The snow ended up floating above empty space.
The fix is a Range over the text, which gives the actual first line of letters:
const range = document.createRange(); range.selectNodeContents(heading); const firstLine = [...range.getClientRects()].find((r) => r.width > 4); const fontSize = parseFloat(getComputedStyle(heading).fontSize); const surface = { left: firstLine.left, width: firstLine.width, top: firstLine.top + fontSize * 0.22, // skip the space above the capitals }; Each surface keeps a height map in 6 px columns. When a flake lands, its column grows and the neighbours grow a little too. The cap is drawn as one smooth white shape over those heights, with individual flakes on top for texture. When a column is full, new flakes slide off the side.
Settled flakes store their position relative to the element, so the snow stays on the heading while you scroll.
6. Shaking on a laptop
Laptops have no motion sensor, so the mouse stands in. A shake is a fast back-and-forth: I count direction changes of quick movements, and four within 900 ms count as a shake.
let lastX = 0, lastT = 0, dir = 0, flips = []; addEventListener("pointermove", (e) => { const now = performance.now(); const dx = e.clientX - lastX; const speed = Math.abs(dx) / Math.max(1, now - lastT); // px per ms lastX = e.clientX; lastT = now; if (speed < 1.1) return; // ignore normal mouse movement if (Math.sign(dx) !== dir) { dir = Math.sign(dx); flips = [...flips.filter((t) => now - t < 900), now]; if (flips.length >= 4) shake(0.6); } }, { passive: true }); 7. Being a polite guest on someone else's page
An effect like this lives on other people's websites, so it has to stay out of the way:
- Everything draws on one
<canvas>withpointer-events: none, so links and buttons keep working. - The button, hint and reward card live in a shadow DOM, so the site's CSS can't break them, and vice versa.
- On light pages, white snow gets a faint cool shadow so it doesn't vanish.
- With
prefers-reduced-motion, the snow starts already settled and shakes are gentler. - It pauses when the tab is hidden, and it sets no cookies.
Try it
- Live demo: shake your phone, or shake your mouse.
- On npm:
npm install @fluritheme/snow-globe - One line of HTML:
<script src="https://cdn.jsdelivr.net/npm/@fluritheme/snow-globe@1/dist/snow-globe.global.js" data-auto></script> Shops can add a small reward for the first shake, like a discount code, and the snow can be gold or glitter.
What would you put inside a snow globe on your site? I'd love to see it if you try it.
![[BOSNIAN LANGUAGE] useState je jednako moćno kao i useReducer](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnwwbmmkrbuxqkz1k9oos.png)