繁体   English   中英

以预定的旋转值旋转命运之轮

[英]Spinning a wheel of fortune with a predetermined rotation value

我的目标是(在单击按钮时)多次旋转轮子,然后以特定的旋转值(0...360)结束,同时缓和动画。 我目前可以“平稳”旋转到车轮上的特定点,而无需任何完整的旋转。 我的问题是尝试多次旋转轮子,然后降落在特定点以使其看起来更逼真。 这可以通过 CSS 动画属性或其他任何东西来实现吗?

这是我的代码...

 const wheelEl = document.getElementById("wheel"); const sliceSize = 360 / 3; function spinWheel(index) { // Reset animation wheelEl.style.transition = "none"; wheelEl.style.transform = "rotate(0deg)"; // Play animation on the next frame setTimeout(() => { wheelEl.style.transition = "all ease 1s"; // Target rotation margin let rotMin = (sliceSize * (index))+(sliceSize/15); let rotMax = (sliceSize * (index + 1))-(sliceSize/15); // Target rotation let rot = Math.floor(Math.random() * (rotMax - rotMin + 1) + rotMin); wheelEl.style.transform = `rotate(-${rot}deg)`; }, 0); }
 #container { position: absolute; text-align: center; } #arrow { position: absolute; top: -5px; left: 50%; transform: translateX(-50%); border-top: 10px solid black; border-left: 8px solid transparent; border-right: 8px solid transparent; z-index: 1; } #wheel { width: 100px; height: 100px; border-radius: 50%; background-image: conic-gradient(lightpink 0 120deg, lightblue 0 240deg, lightsalmon 0 360deg); }
 <div id="container"> <div id="arrow"></div> <div id="wheel"></div> <br /> <button onclick="spinWheel(2)">Spin wheel</button> </div>

您可以坚持使用转换。

此代码段做了两件事:将 360 度的随机数(在界限内)添加到旋转值,并将缓动函数设置为缓出,以便旋转仅在接近尾声时减慢。

为了可以看到效果,完全旋转的时间设置为 5 秒,但当然可以将其更改为您想要的任何内容。 例如,如果需要,您也可以在某些范围内随机设置。

如果说你想要更长的时间看起来慢下来,你也可以使用代表缓出的 Beziere 函数。

 const wheelEl = document.getElementById("wheel"); const sliceSize = 360 / 3; function spinWheel(index) { // Reset animation wheelEl.style.transition = "none"; wheelEl.style.transform = "rotate(0deg)"; // Play animation on the next frame setTimeout(() => { wheelEl.style.transition = "all ease-out 5s"; // Target rotation margin const rotMin = (sliceSize * (index)) + (sliceSize / 15); const rotMax = (sliceSize * (index + 1)) - (sliceSize / 15); // Target rotation const fullRots = Math.floor(Math.random() * 5) + 5; // minimum 5 rotations max 9 const rot = (fullRots * 360) + Math.floor(Math.random() * (rotMax - rotMin + 1) + rotMin); wheelEl.style.transform = `rotate(-${rot}deg)`; }, 0); }
 #container { position: absolute; text-align: center; } #arrow { position: absolute; top: -5px; left: 50%; transform: translateX(-50%); border-top: 10px solid black; border-left: 8px solid transparent; border-right: 8px solid transparent; z-index: 1; } #wheel { width: 100px; height: 100px; border-radius: 50%; background-image: conic-gradient(lightpink 0 120deg, lightblue 0 240deg, lightsalmon 0 360deg); }
 <div id="container"> <div id="arrow"></div> <div id="wheel"></div> <br /> <button onclick="spinWheel(2)">Spin wheel</button> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM