Are Svelte transitions/animations done with CSS or JS?
Asked Answered
S

1

7

I'm checking out Svelte, and I'm finding a lot more out of the box that I would've expected.

One thing that surprised me a little bit where the amount of transition and animation tools, especially the tooling for custom transitions, and I can't quite tell from their syntax if these are functions that write CSS, or if they're functions that manipulate styles directly with a CSS-like syntax.

Are the resulting animations CSS only or not?

Sigismondo answered 13/5, 2019 at 7:26 Comment(0)
R
15

The short answer: CSS.

The longer answer: When a transition function is called, it returns an object with the transition object, which must include a css method, a tick method, or both. The tick method is straightforward — it is called every frame (using requestAnimationFrame, essentially) until the transition has completed, allowing you do things that are impossible just with CSS, like a typewriter effect.

The css method works differently. Say you have a simple fade transition that returns a function like this:

css: t => `opacity: ${t}`

(This is almost exactly what the built-in fade transition does.) This function will be called multiple times with a different value of t before the transition begins — the number of times depends on the duration of the transition — so that a set of keyframes are generated:

keyframes = [
  '0% { opacity: 0 }',
  '10% { opacity: 0.1 }',
  '20% { opacity: 0.2 }',
  // ...
];

Those keyframes are then joined together into a CSS animation and applied to the element.

In that simple example, it might seem over-engineered — after all, we could just go from 0% { opacity: 0 } to 100% { opacity: 1 }. But it gives us the power to build custom transitions with easing functions that aren't normally available in CSS animations, all without resorting to manipulating styles in JavaScript (which must happen on the main thread, creating a common source of jank.)

Rosenfeld answered 13/5, 2019 at 12:23 Comment(2)
Thanks! Just to clarify: if I understand you correctly, a tick method will manipulate styles in JavaScript but it is there to provide effects CSS itself simply cannot do?Intolerable
It can manipulate styles, or change some state, or log something to the console — whatever you want. It's just there as an escape hatch for when CSS isn't powerful enough.Rosenfeld

© 2022 - 2024 — McMap. All rights reserved.