How to draw a 3D dice that rotates constantly?
With CSS, it is as simple as to create 6 div
s, each div
is responsible for drawing one plane. CSS has many transform functions that can be helpful doing all sorts of rotations, skews and resizing.
The trick for creating this 3D figure is to add in one
div
element at a time. Starting from the 'front' plane, this plane has no rotation, only a translate on Z axis with a distance of half of the cube side length, this will move the front plane 100px towards the user. All planes on five other sides should have a rotation of 90 degrees on either x or y axis, as well as a 100px translate on x, y or z axis. This requires a bit of playing-around to finally make the moves right.
Here is the code:
*** index.html
<div class="shape">
<div class="face front">1</div>
<div class="face back">2</div>
<div class="face top">3</div>
<div class="face left">4</div>
<div class="face right">5</div>
<div class="face bottom">6</div>
</div>
*** style.scss
.shape {
width:200px;
height: 200px;
transform-style: preserve-3d;
transform: rotate3d(1,1,1,30deg);
transition: transform 1.5s;
margin: 50px 100px;
animation: rotateMe 2s 3s ease-in-out infinite,
}
@keyframes rotateMe {
50% {
transform: rotate(180deg) scale(.5);
}
}
.face {
// background:rgb(227, 246, 15);
// for setting number at the center
display: flex;
align-items: center;
justify-content: center;
font-size: 10rem;
color: white;
// for position
position: absolute; //default position
backface-visibility:inherit;
// backface-visibility: hidden;
width: 100%;
height:100%;
border-radius: 50px;
}
.front {
background:rgba(219, 6, 6, 0.5);
transform: translateZ(100px); // half of the face width, move towards user
}
.back {
background: rgba(3, 63, 205, 0.5);
transform: rotateY(180deg) translateZ(100px); // flip by 180deg, so this move is away from the user, but towards the user of 180deg angle
}
.left {
background: rgb(242, 219, 8,.5);
transform: translateX(-100px) rotateY(-90deg);
}
.right {
background: rgba(33, 3, 155, 0.5);
transform: translateX(100px) rotateY(90deg);
}
.top {
background: rgba(6, 225, 50, 0.5);
transform: translateY(-100px) rotateX(-90deg);
}
.bottom {
background: rgb(242, 8, 226, .5);
transform: translateY(100px) rotateX(-90deg);
}
To see the code in action, check out the codepen:
See the Pen
Dice with css transform by Susan G (@Koo8)
on CodePen.