Skip to content

Commit 19a3425

Browse files
Bikram GoleBikram Gole
authored andcommitted
Optimize ambient animations
1 parent 9a2b15b commit 19a3425

1 file changed

Lines changed: 19 additions & 7 deletions

File tree

script.js

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ const canvas = document.getElementById("starfield");
184184
const ctx = canvas?.getContext("2d");
185185
let stars = [];
186186
let lastStarFrame = 0;
187+
let starsAnimation = null;
187188
const runtimeFlags = {
188189
isConstrained: false,
189190
isFirefoxLike: false,
@@ -236,16 +237,15 @@ function resizeCanvas() {
236237

237238
function drawStars(timestamp = 0) {
238239
if (!canvas || !ctx) return;
239-
const profile = getStarFieldProfile();
240-
const elapsed = timestamp - lastStarFrame;
241-
242240
if (document.hidden) {
243-
requestAnimationFrame(drawStars);
241+
starsAnimation = null;
244242
return;
245243
}
244+
const profile = getStarFieldProfile();
245+
const elapsed = timestamp - lastStarFrame;
246246

247247
if (elapsed < profile.frameBudget) {
248-
requestAnimationFrame(drawStars);
248+
starsAnimation = requestAnimationFrame(drawStars);
249249
return;
250250
}
251251

@@ -266,16 +266,28 @@ function drawStars(timestamp = 0) {
266266
ctx.fill();
267267
});
268268

269-
requestAnimationFrame(drawStars);
269+
starsAnimation = requestAnimationFrame(drawStars);
270270
}
271271

272272
resizeCanvas();
273273
window.addEventListener("resize", resizeCanvas);
274274
if (!prefersReducedMotion) {
275-
requestAnimationFrame(drawStars);
275+
starsAnimation = requestAnimationFrame(drawStars);
276276
}
277+
document.addEventListener("visibilitychange", () => {
278+
if (document.hidden) {
279+
if (starsAnimation) cancelAnimationFrame(starsAnimation);
280+
starsAnimation = null;
281+
return;
282+
}
283+
if (!prefersReducedMotion && !starsAnimation) {
284+
starsAnimation = requestAnimationFrame(drawStars);
285+
}
286+
});
277287

278288
function attachTiltBehavior(card) {
289+
if (prefersReducedMotion) return;
290+
if (window.matchMedia && !window.matchMedia("(hover: hover)").matches) return;
279291
let tiltFrame = null;
280292
let lastMouseEvent = null;
281293
const reset = () => {

0 commit comments

Comments
 (0)