Motion Values
Animate everything based on user input.
Similar to a hook in React, you can define motion values in the script
section of your component:
import { useMotionValue } from "svelte-motion";
const x = useMotionValue(0);
The motion value can be injected via the style
prop of the Motion
components.
<Motion drag style={{x}} use:motion>...</Motion>
For more information about the motion value API you can look into the documentation of Framer Motion.
Additionally, motion values implement Sveltes writable store API, which means you can use auto-subscription, update
, set
and subscribe
.
In the following example, the border-radius
and opacity
is adjusted based on the horizontal position. The values are extracted with Sveltes auto-subscription.
In this REPL is another example with SVG draw animations:
Reset
Motion values should be defined when the svelte component is initialized. That means the initial definition should be inside the script
tags and not within a reacive statement ($:
). If you need to change the props of a derived motion value, you can use the reset
method. It is available on all derived motion values:
- useTransform
- useVelocity
- useSpring
- useMotionTemplate
Velocity
With useVelocity
the velocity of a motion value can be extracted and used further:
import { useMotionValue, useVelocity } from "svelte-motion";
const x = useMotionValue(0)
const velocity = useVelocity(x)
In the following example the color becomes more intense the faster you drag it:
Motion Template
With useMotionTemplate
you can combine several motion values via a javascript string template.
import { Motion, useMotionValue, useMotionTemplate } from "svelte-motion";
const x = useMotionValue(0);
const y = useMotionValue(0);
const shadow = useMotionTemplate`drop-shadow(${x}px ${y}px 20px rgba(0,0,0,0.8))`
See how the shadow moves when you drag the box:
Scroll
With useViewportScroll
you can get motion values for the scrolling of the outer viewport and with useElementScroll
you can use the scroll values from a certain html element. To provide a ref
to useElementScroll
you have two options:
- Implement React like ref:
import { useElementScroll } from 'svelte-motion'
const ref = {}
const scrollMotionValue = useElementScroll(ref)
<div bind:this={ref.current}>...</div>
- Set motion value
ref
attribute:
import { useElementScroll } from 'svelte-motion'
const scrollMotionValue = useElementScroll();
<div bind:this={scrollMotionValue.ref}>...</div>