使用KeyFrames中的React中的随机启动位置旋转图像
使用React,我有一个要开始从随机位置旋转并无限旋转360度的组件。我所拥有的是:
html:
return <img className={`${props.className}`} style={{
animation: `spin 5s linear infinite`,
transform: `rotate(${Math.floor(Math.random() * (361));}deg)`
}} src={image} alt="img"/>
CSS:
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
默认情况下,它的作用是忽略变换,加载图像以使其直立(即0度),然后在5秒钟内旋转到360度(垂直方向)。我想要的是一种从变换中的方法:旋转(deg);} and be {transform:rotate(&lt;某些随机数 + 360&gt; deg);} < /strong>。这可能吗?
作为旁注,是否可以随机将其行驶的方向随机化吗?
Using React, I have a component that I want to start rotated from a random location and rotate 360 degrees infinitely. What I have is:
HTML:
return <img className={`${props.className}`} style={{
animation: `spin 5s linear infinite`,
transform: `rotate(${Math.floor(Math.random() * (361));}deg)`
}} src={image} alt="img"/>
CSS:
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
By default, what this does is ignore the transform, load the image so that it is upright (i.e. 0 degrees), and rotate to 360 degrees (vertical again) over the course of 5 seconds. What I want is a way for from to be transform:rotate(deg);} and to to be {transform:rotate(<SOME RANDOM NUMBER + 360>deg);}. Is this possible?
As a side note, is it possible to randomize the direction it travels?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法使用变换旋转获得所需的效果 - 正如您注意到的那样,动画会立即将其更改为
旋转(0)
。但是,您可以做的是利用
animation-delay
css属性。而不是计算随机旋转,而是在0到5秒之间计算一个随机时间,然后使用否定的时间来设置
and> and> Animation-delay
。该动画将在其周期,随机点和因此以随机角度。这是一个纯CSS/HTML/JS片段,旋转放慢速度,因此更容易看到旋转每次都以不同的角度启动:
You can't get the required effect using transform rotate - as you have noted the animation will immediately alter this to
rotate(0)
.But what you can do is leverage the
animation-delay
CSS property.Instead of calculating a random rotation, calculate a random time between 0 and 5 seconds and use that, negative, to set
animation-delay
.The animation will start part way through its cycle, at a random point and so at a random angle.Here's a pure CSS/HTML/JS snippet with the rotation slowed down so it's easier to see that the rotation does start at a different angle each time: