I'm working on a rock paper scissors game. When I click a button I have it where two images do a "shake" animation to simulate the hand motions done during a real game. This is all fine, however the image on the right flips horizontally during the animation but flips back at the end. I initially have it flipped so both hands face each other.
I'm wondering if it's possible to prevent that second image from flipping during the animation.
HTML
<div >
<div >
<p >Player Options: </p>
<div >
<button onclick="animation()"><img src="img/rock.jpg" alt="Rock Sign" width="100" height="100" id="player-img-main"></button>
<button><img src="img/paper.jpg" alt="Rock Sign" width="100" height="100" ></button>
<button><img src="img/scissors.jpg" alt="Rock Sign" width="100" height="100" ></button>
</div>
</div>
<div >
<div >
<img src="img/rock.jpg" alt="Rock Sign" width="100" height="100" id="computer-img-main">
<img src="img/paper.jpg" alt="Rock Sign" width="100" height="100" id="computer-img">
<img src="img/scissors.jpg" alt="Rock Sign" width="100" height="100" id="computer-img">
</div>
<p > :Computer Options</p>
</div>
</div>
Javascript
function animation() {
const element = document.getElementById('player-img-main');
const element2 = document.getElementById('computer-img-main');
element.classList.remove('shake'); // reset animation
element2.classList.remove('shake'); // reset animation
void element.offsetWidth; // trigger reflow
void element2.offsetWidth; // trigger reflow
element.classList.add('shake'); // start animation
element2.classList.add('shake'); // start animation
}
CSS
#computer-img-main {
transform: scaleX(-1); /* Flip image horizontally */
}
.shake {
animation-name: shake;
animation-iteration-count: 1;
animation-duration: 2s;
animation-fill-mode: both;
}
@keyframes shake {
3%, 21%, 39%, 57%, 74%, 92% { transform: translateY(5px) }
6%, 24%, 42%, 60%, 77%, 95% { transform: translateY(3px) }
9%, 27%, 45%, 63%, 80%, 98% { transform: translateY(-5px) }
}
CodePudding user response:
You can keep the HTML structure as it is, and share the keyframes, but you need to remember what the scaling is (the flipping of the hand image) and make sure that is in any transform that is done.
You could use a CSS variable for this. e.g. here we set --s to 1 for the player side and to -1 for the computer side. And then in the transforms in the keyframes we add in scaleX(var(--s)).
#player-img-main {
--s: 1;
}
#computer-img-main {
transform: scaleX(-1);
--s: -1;
/* Flip image horizontally */
}
.shake {
animation-name: shake;
animation-iteration-count: 1;
animation-duration: 2s;
animation-fill-mode: both;
}
@keyframes shake {
3%,
21%,
39%,
57%,
74%,
92% {
transform: scaleX(var(--s)) translateY(5px)
}
6%,
24%,
42%,
60%,
77%,
95% {
transform: scaleX(var(--s)) translateY(3px)
}
9%,
27%,
45%,
63%,
80%,
98% {
transform: scaleX(var(--s)) translateY(-5px)
}
}