User Tools

Site Tools


java-script:fun:3d-spinning-cube

3D Spinning Cube in HTML, CSS and JS

cube.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive 3D Cube</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f0f0;
        }
 
        .cube-container {
            width: 200px;
            height: 200px;
            perspective: 800px;
        }
 
        .cube {
            position: relative;
            width: 100%;
            height: 100%;
            transform-style: preserve-3d;
            transition: transform 0.5s ease-in-out;
        }
 
        .face {
            position: absolute;
            width: 100%;
            height: 100%;
            border: 2px solid #333;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            color: white;
        }
 
        .front { background-color: rgba(0, 0, 255, 0.7); transform: rotateY(0deg) translateZ(100px); }
        .back { background-color: rgba(255, 0, 0, 0.7); transform: rotateY(-180deg) translateZ(100px); }
        .right { background-color: rgba(0, 255, 0, 0.7); transform: rotateY(-90deg) translateZ(100px); }
        .left { background-color: rgba(255, 255, 0, 0.7); transform: rotateY(90deg) translateZ(100px); }
        .top { background-color: rgba(255, 0, 255, 0.7); transform: rotateX(90deg) translateZ(100px); }
        .bottom { background-color: rgba(0, 255, 255, 0.7); transform: rotateX(-90deg) translateZ(100px); }
    </style>
</head>
<body>
    <div class="cube-container">
        <div class="cube" id="cube">
            <div class="face front">Front</div>
            <div class="face back">Back</div>
            <div class="face right">Right</div>
            <div class="face left">Left</div>
            <div class="face top">Top</div>
            <div class="face bottom">Bottom</div>
        </div>
    </div>
 
    <script>
        const cube = document.getElementById('cube');
 
        function rotateCube() {
            let angleX = 0;
            let angleY = 0;
            const rotationSpeed = 2; // degrees per frame
 
            function animate() {
                angleX += rotationSpeed;
                angleY += rotationSpeed;
                cube.style.transform = `rotateX(${angleX}deg) rotateY(${angleY}deg)`;
                requestAnimationFrame(animate);
            }
 
            animate();
        }
 
        cube.addEventListener('mouseenter', () => {
            rotateCube();
        });
    </script>
</body>
</html>

java-script/fun/3d-spinning-cube.txt · Last modified: 2024/08/14 04:33 by odefta