Fiddle : https://jsfiddle.net/7p9uv16b/
I have few blocks rotated with different angles at start. I want to translate them along the rotated axis, on click. But the translation animation reset the rotation angle. I know that I can chain transformation to rotate + translate, but I need multiple animations for that (one per block). Do CSS provides a way to keep the current state as reference for new transformation ?
Html:
<button type="button" onclick="move()">
Animate blocks
</button>
<button type="button" onclick="reset()">
Reset
</button>
<div id="s1" class="square">
</div>
<div id="s2" class="square">
</div>
CSS:
.square{
height: 50px;
width: 50px;
background-color: #58ACFA;
margin: 100px;
}
.move{
-webkit-animation: move 2s both;
animation: move 2s both;
}
@-webkit-keyframes move {
0% {
-webkit-transform: translateX(0);
transform: translateX(0);
}
100% {
-webkit-transform: translateX(100px);
transform: translateX(100px);
}
}
@keyframes move {
0% {
-webkit-transform: translateX(0);
transform: translateX(0);
}
100% {
-webkit-transform: translateX(100px);
transform: translateX(100px);
}
}
Javascript:
$('#s1').css('transform','rotate(45deg)');
$('#s2').css('transform','rotate(30deg)');
function move(){
$('.square').addClass('move');
}
function reset(){
$('.square').removeClass('move');
}
You can use CSS variables.
.square {
--position: 0px;
--angle: 0deg;
-webkit-transform: translateX(var(--position)) rotate(var(--angle));
transform: translateX(var(--position)) rotate(var(--angle));
}
#s1 {
--angle: 45deg;
}
#s2 {
--angle: 30deg;
}
@keyframes move {
0% {
--position: 0px;
}
100% {
--position: 100px;
}
}