跳到主要內容

spring 函式是 tweened 的替代方案,通常對於頻繁變更的值效果更好。

在這個範例中,我們有兩個儲存 — 一個表示圓形的座標,另一個表示它的大小。讓我們將它們轉換為彈簧

App
<script>
	import { spring } from 'svelte/motion';

	let coords = spring({ x: 50, y: 50 });
	let size = spring(10);
</script>

兩個彈簧都有預設的 stiffnessdamping 值,它們控制彈簧的,嗯... 彈性。我們可以指定自己的初始值

App
let coords = spring({ x: 50, y: 50 }, {
	stiffness: 0.1,
	damping: 0.25
});

在滑鼠周圍擺動滑鼠,並嘗試拖曳滑桿以感受它們如何影響彈簧的行為。請注意,您可以在彈簧仍在運動時調整這些值。

在 GitHub 上編輯此頁面

上一個 下一個
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<script>
	import { writable } from 'svelte/store';
 
	let coords = writable({ x: 50, y: 50 });
	let size = writable(10);
</script>
 
<svg
	onmousemove={(e) => {
		coords.set({ x: e.clientX, y: e.clientY });
	}}
	onmousedown={() => size.set(30)}
	onmouseup={() => size.set(10)}
	role="presentation"
>
	<circle
		cx={$coords.x}
		cy={$coords.y}
		r={$size}
	/>
</svg>
 
<div class="controls">
	<label>
		<h3>stiffness ({coords.stiffness})</h3>
		<input
			bind:value={coords.stiffness}
			type="range"
			min="0.01"
			max="1"
			step="0.01"
		/>
	</label>
 
	<label>
		<h3>damping ({coords.damping})</h3>
		<input
			bind:value={coords.damping}
			type="range"
			min="0.01"
			max="1"
			step="0.01"
		/>
	</label>
</div>
 
<style>
	svg {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
	}
 
	circle {
		fill: #ff3e00;
	}
 
	.controls {
		position: absolute;
		top: 1em;
		right: 1em;
		width: 200px;
		user-select: none;
	}
 
	.controls input {
		width: 100%;
	}
</style>