The spring
function is an alternative to tweened
that often works better for values that are frequently changing.
In this example we have two stores — one representing the circle's coordinates, and one representing its size. Let's convert them to springs:
<script>
import { spring } from 'svelte/motion';
let coords = spring({ x: 50, y: 50 });
let size = spring(10);
</script>
Both springs have default stiffness
and damping
values, which control the spring's, well... springiness. We can specify our own initial values:
let coords = spring({ x: 50, y: 50 }, {
stiffness: 0.1,
damping: 0.25
});
Waggle your mouse around, and try dragging the sliders to get a feel for how they affect the spring's behaviour. Notice that you can adjust the values while the spring is still in motion.
App.svelte
xxxxxxxxxx
31
1
<script>
2
import { writable } from 'svelte/store';
3
4
let coords = writable({ x: 50, y: 50 });
5
let size = writable(10);
6
</script>
7
8
<style>
9
svg { width: 100%; height: 100%; margin: -8px; }
10
circle { fill: #ff3e00 }
11
</style>
12
13
<div style="position: absolute; right: 1em;">
14
<label>
15
<h3>stiffness ({coords.stiffness})</h3>
16
<input bind:value={coords.stiffness} type="range" min="0" max="1" step="0.01">
17
</label>
18
19
<label>
Console
xxxxxxxxxx
206
1
/* App.svelte generated by Svelte v3.23.2 */
2
import {
3
SvelteComponent,
4
append,
5
attr,
6
component_subscribe,
7
detach,
8
element,
9
init,
10
insert,
11
listen,
12
noop,
13
run_all,
14
safe_not_equal,
15
set_data,
16
set_input_value,
Compiler options
result = svelte.compile(source, {
generate:
});xxxxxxxxxx
1
1
svg.svelte-1mcxoeq{width:100%;height:100%;margin:-8px}circle.svelte-1mcxoeq{fill:#ff3e00 }