【发布时间】:2020-01-30 09:19:42
【问题描述】:
我有几十个 png 文件(大小相同),并希望将它们用于简单的动画。 (图片取自经典的“xneko”程序。)
现在,我的 neko.svelte 看起来像:
<script>
export let position = {left: 100, top: 100};
let current = 0;
let names = [
'awake', 'down1', 'down2', 'dtogi1', 'dtogi2', 'dwleft1', 'dwleft2',
'dwright1', 'dwright2', 'jare2', 'kaki1', 'kaki2', 'left1', 'left2',
'ltogi1', 'ltogi2', 'mati2', 'mati3', 'right1', 'right2', 'rtogi1', 'rtogi2',
'sleep1', 'sleep2', 'up1', 'up2', 'upleft1', 'upleft2',
'upright1', 'upright2', 'utogi1', 'utogi2'
];
setInterval(() => current = (current + 1) % names.length, 100);
</script>
<style>
.neko {
position: relative;
}
</style>
<div class='neko' style="
left: {position.left + 'px'};
top: {position.top + 'px'};
width: 32px;
height: 32px;">
{#each names as name (name)}
<img id={name} width=32 height=32
style='display: {names[current] === name ? "inherit" : "none"}'
src={'https://tinlizzie.org/~ohshima/neko/neko/' + name + '.png'} alt={name}/>
{/each}
</div>
(选择图像的实际逻辑涉及更多,但为了说明目的,此处对其进行了简化。position 是从拥有的组件传入的。您可以在此处看到它运行:https://tinlizzie.org/~ohshima/neko/)
这工作正常。但我想知道是否有比在显示场景中必须显示所有 img 元素但不使用display: none 来显示其中一个更好的方法。如果它是在直接 DOM 中完成的,它会创建 img 元素的列表并将其中一个附加到 div 中。但似乎我不能写这样的东西:
<script>
let allImages = ...; // a dictionary of img elements
let currentImg = allIamges[name]; // an img element
</script>
<div class='neko'>{currentImg}</div> // reference to the img
请让我知道做这样的精灵动画的建议方法是什么。
【问题讨论】:
标签: image animation dom svelte