How to use CSS Transforms and Transitions In Javascript
This approach enhances the cube’s interactivity by incorporating JavaScript to handle user interactions. We use CSS transforms to rotate the cube and position content on each face, while JavaScript manages user interaction to trigger rotations along different axes. CSS transitions are applied for smooth animations.
Example: The below code implements CSS properties and JavaScript to create a viewer cube.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>CSS Viewer Cube</title>
<link rel="stylesheet" href="style.css">
</head>
<body style="text-align: center;">
<h2>
Below is the CSS viewer cube
created using JavaScript
</h2>
<div class="cube-container">
<div class="cube">
<div class="face front">Front</div>
<div class="face back">Back</div>
<div class="face top">Top</div>
<div class="face bottom">Bottom</div>
<div class="face left">Left</div>
<div class="face right">Right</div>
</div>
</div>
<script>
document.addEventListener
('DOMContentLoaded', function () {
const cube = document.
querySelector('.cube');
let angleX = 0;
let angleY = 0;
function rotateCube() {
angleX += 1;
angleY += 1;
cube.style.transform =
`rotateX(${angleX}deg)
rotateY(${angleY}deg)`;
requestAnimationFrame(rotateCube);
}
rotateCube();
});
</script>
</body>
</html>
.cube-container {
perspective: 600px;
width: 200px;
height: 200px;
margin: 100px auto;
}
.cube {
position: relative;
width: 100%;
height: 100%;
transform-style: preserve-3d;
transition: transform 1s ease-in-out;
}
.face {
position: absolute;
width: 200px;
height: 200px;
background-color: rgba(255, 255, 255, 0.8);
border: 2px solid #333;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
}
.front {
transform: translateZ(100px);
}
.back {
transform: rotateY(180deg) translateZ(100px);
}
.top {
transform: rotateX(90deg) translateZ(100px);
}
.bottom {
transform: rotateX(-90deg) translateZ(100px);
}
.left {
transform: rotateY(-90deg) translateZ(100px);
}
.right {
transform: rotateY(90deg) translateZ(100px);
}
Output:
CSS Viewer Cube without Three.js using Vanilla JavaScript
Creating a CSS viewer cube without three.js using Vanilla JavaScript offers a lightweight alternative for rendering 3D cubes in web applications. This article explores various approaches to implementing a CSS viewer cube without relying on three.js, providing developers with flexibility and simplicity.
These are the following approaches:
Table of Content
- Creating Cube with HTML and CSS
- Using CSS Transforms and Transitions
- Using CSS Grid and Flexbox