Svelte Spring

2023-02-21 17:31 更新

?spring? 函數(shù)是 ?tweened? 的替代方法,對于經(jīng)常變化的值通常效果更好。

在這個例子中,我們有兩個 stores——一個代表圓的坐標(biāo),一個代表它的大小。讓我們將它們轉(zhuǎn)換為 springs:

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

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

兩個 springs 都有默認(rèn)的 ?stiffness?和 ?damping?,它們控制 spring 的…… springiness。我們可以指定我們自己的初始值:

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

左右搖動鼠標(biāo),并嘗試拖動滑塊以了解它們?nèi)绾斡绊?spring 的行為。請注意,您可以在 spring 仍在運動時調(diào)整這些值。

示例代碼

  • App.svelte

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

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

	let size = spring(10);
</script>

<style>
	svg { width: 100%; height: 100% }
	circle { fill: #ff3e00 }
</style>

<div style="position: absolute; right: 1em;">
	<label>
		<h3>stiffness ({coords.stiffness})</h3>
		<input bind:value={coords.stiffness} type="range" min="0" max="1" step="0.01">
	</label>

	<label>
		<h3>damping ({coords.damping})</h3>
		<input bind:value={coords.damping} type="range" min="0" max="1" step="0.01">
	</label>
</div>

<svg
	on:mousemove="{e => coords.set({ x: e.clientX, y: e.clientY })}"
	on:mousedown="{() => size.set(30)}"
	on:mouseup="{() => size.set(10)}"
>
	<circle cx={$coords.x} cy={$coords.y} r={$size}/>
</svg>


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號