Issue
I want to spin an image and after 3 seconds it must stop at a random angle (from 360
to 10800
degrees). It should start to spin from the last position when it is clicked.
When the image stops spinning, a random citation should appear in a nearby area. I am trying to achieve an effect like "spin the bottle"
I want to use CSS or JavaScript. Here is my code so far:
.wheel {
animation: wheel 3s .5s;
animation-fill-mode: both;
}
@keyframes wheel {
from {
transform: rotate(0);
}
to {
transform: rotate(10800deg);
}
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">
Solution
You can do this with css custom properties. The first thing to do is create a property for your transform:
:root{
--rot: rotate(108000deg);
}
And then use that in place of your hard-coded value
@keyframes wheel {
from { transform: rotate(0);}
to { transform: var(--rot); }
}
At this stage everything should carry on working as before.
Now you can manipulate that property with javascipt:
var min = 360;
var max = 108000;
var rnd = Math.random()* (max - min) + min;
console.log(rnd);
var wheel = document.querySelector(".wheel");
wheel.style.setProperty("--rot","rotate(" + rnd + "deg)");
:root{
--rot: rotate(108000deg);
}
.wheel {
animation: wheel 3s .5s;
animation-fill-mode: both;
}
@keyframes wheel {
from { transform: rotate(0);}
to { transform: var(--rot); }
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" class="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">
If you want to repeat the animation on something like a click you need to doa bit of a workaround
var min = 360;
var max = 108000;
var wheel = document.querySelector("#wheel");
wheel.addEventListener("click", function(e) {
e.preventDefault;
// -> removing the class
wheel.classList.remove("wheel");
// -> triggering reflow /* The actual magic */
// without this it wouldn't work. Try uncommenting the line and the transition won't be retriggered.
// Oops! This won't work in strict mode. Thanks Felis Phasma!
// element.offsetWidth = element.offsetWidth;
// Do this instead:
void wheel.offsetWidth;
var rnd = Math.random()* (max - min) + min;
console.log(rnd);
wheel.style.setProperty("--rot","rotate(" + rnd + "deg)");
// -> and re-adding the class
wheel.classList.add("wheel");
}, false);
:root{
--rot: rotate(108000deg);
}
.wheel {
animation: wheel 3s .5s;
animation-fill-mode: both;
}
@keyframes wheel {
to { transform: var(--rot); }
}
<head>
<link rel="stylesheet" href="bottle.css">
<script src="bottle.js"></script>
</head>
<img id="wheel" src="https://cdn.iconscout.com/icon/free/png-256/grinning-face-smile-emoji-happy-37705.png">
Answered By - Jamiec
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.