Spring 类是 Tween 的替代品,通常更适合经常变化的值。
¥The Spring class is an alternative to Tween that often works better for values that are frequently changing.
在这个例子中,我们有一个跟随鼠标的圆圈,以及两个值 — 圆圈的坐标和它的大小。让我们将它们转换为弹簧:
¥In this example we have a circle that follows the mouse, and two values — the circle’s coordinates, and its size. Let’s convert them to springs:
<script>
import { Spring } from 'svelte/motion';
let coords = new Spring({ x: 50, y: 50 });
let size = new Spring(10);
</script><script lang="ts">
import { Spring } from 'svelte/motion';
let coords = new Spring({ x: 50, y: 50 });
let size = new Spring(10);
</script>与 Tween 一样,spring 具有可写的 target 属性和只读的 current 属性。更新事件处理程序...
¥As with Tween, springs have a writable target property and a readonly current property. Update the event handlers...
<svg
onmousemove={(e) => {
coords.target = { x: e.clientX, y: e.clientY };
}}
onmousedown={() => (size.target = 30)}
onmouseup={() => (size.target = 10)}
role="presentation"
>...和 <circle> 属性:
¥...and the <circle> attributes:
<circle
cx={coords.current.x}
cy={coords.current.y}
r={size.current}
></circle>两个 spring 都有默认的 stiffness 和 damping 值,它们控制着 spring 的……弹性。我们可以指定自己的初始值:
¥Both springs have default stiffness and damping values, which control the spring’s, well... springiness. We can specify our own initial values:
let coords = new 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.
<script>
let coords = $state({ x: 50, y: 50 });let size = $state(10);
</script>
<svg
onmousemove={(e) => { coords = { x: e.clientX, y: e.clientY };}}
onmousedown={() => (size = 30)} onmouseup={() => (size = 10)}role="presentation"
>
<circle
cx={coords.x} cy={coords.y} r={size}></circle>
</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>