Svelte基础
Svelte高阶
上下文API
特殊元素
接下来
SvelteKit基础
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
Spring(弹簧) 类是 Tween(插值) 的替代方案,通常更适合处理频繁变化的值。
在此示例中,我们有一个跟随鼠标移动的圆,以及两个值——圆的坐标和大小。让我们将它们转换为弹簧:
The
Springclass is an alternative toTweenthat 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 类似,弹簧具有一个可写的 target 属性和一个只读的 current 属性。更改事件处理程序:
As with
Tween, springs have a writabletargetproperty and a readonlycurrentproperty. 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>两个弹簧都使用默认的stiffness(硬度) 和 damping(阻尼,衰减系数) 值,这些值控制弹簧的特性。我们可以指定自己的初始值:
Both springs have default
stiffnessanddampingvalues, 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>