Kevin Rajan Kevin Rajan - 5 months ago 17
Javascript Question

Create a folding animation of a simple square

I'm pretty new to web dev and animation in general, so please excuse me if this is trivial. I am trying to make this animation. This animation is quite complicated, but all I would like to do is fold a square in half showing the folding animation.

I have visited this website and I tried to use the skew function in order to create the animation.

This is the code I have used so far:



.elementLeft {
display: inline-block;
background-color: #aaaaaa;
height: 100px;
width: 100px;
font-size: 1px;
animation: shakeback 2s infinite;
animation-direction: alternate;
color: white;
}
.elementRight {
display: inline-block;
background-color: #aaaaaa;
height: 100px;
width: 100px;
/* transform: skew(20deg); */
font-size: 1px;
color: white;
animation: shake 2s infinite;
animation-direction: alternate;
}
@keyframes shake {
0% {
transform: skewY(0deg);
}
100% {
transform: skewY(45deg);
}
}
@keyframes shakeback {
0% {
transform: skewY(0deg);
}
100% {
transform: skewY(-45deg);
}
}
body,
html {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}

<div class="elementLeft"></div>
<div class="elementRight">
</div>





However, this is not exactly what I want since the skew function also makes the square too long as I increase the degree. I have been thinking of another way to create this animation, but I am not sure what to do. I also would prefer that only one side folds in rather than both sides folding. This is like in the Google Calendar Icon animation posted above where the top half of the icon stays still whereas the bottom half folds upwards.
Any advice is appreciated and thanks in advanced!

edit: I have also noticed that I can rotate a square upwards to form this effect. However, I am still having an issue as the animation does not look as smooth as I would like.

Any help is once again appreciated!



.element {
display: inline-block;
background-color: #000000;
height: 100px;
width: 100px;
}
.elementfold {
/* transform: rotateX(0deg); */
animation: foldup 5s;
display: inline-block;
background-color: #aaaaaa;
height: 100px;
width: 100px;
}
@keyframes foldup {
0% {
transform: rotateX(0);
}
100% {
transform: rotateX(180deg) translate(0px, 100px);
}
}

<li>
<div class="element"></div>
</li>
<li>
<div class="elementfold"></div>
</li>




Answer

Code:

#container {
  width: 100px;
  height: 100px;
  perspective: 300px;
}

.square {
  width: 100px;
  height: 100px;
  background-color: grey;
}

#animation {
  animation: anim 2s linear 0s infinite alternate;
  transform-origin: 50% 100%;
}

@keyframes anim {
  from {transform: rotateX(0deg);}
  to {transform: rotateX(-180deg);}
}
<div id="container">
  <div class="square" id="animation"></div>
  <div class="square"></div>
</div>

Using CSS3's rotateX property and animations, it's pretty easy to create folding squares.