궁금한게 많은 코린이의 Developer 노트

[Css] 3D 오브젝트 회전시키기 본문

css

[Css] 3D 오브젝트 회전시키기

lemonarr🍋 2023. 12. 18. 23:55

 

3D 오브젝트 회전시킨다..언뜻보면 간단해 보일 수 있겠지만

저는 구현원리를 이해하면 코딩이 더욱 재밌어지더라구요!

(ㅎㅎ..저만 그런건가요😅)

구현 원리를 이해하시면 더욱 재미있고 기억에 잘 남습니다. 

 

 

Css 3D 오브젝트가 어떻게 만들어지는지,

어떻게 회전을 시키는지 한번 알아보도록 하겠습니다.

 

 

구현 화면입니다.

 

3D 오브젝트 회전시키기

 

구현코드

 

Html

 

<body>

    <div id="wrap">
        <div class="container">
        <div class="box front">front</div>
        <div class="box back">back</div>
        <div class="box top">top</div>
        <div class="box bottom">bottom</div>
        <div class="box left">left</div>
        <div class="box right">right</div>
    </div>
    </div>
    
</body>

▲정육면체의 단면들을 감싸는 div 태그를 만들어 한 번 감싸줍니다.

 

 

Css

 

<style>
        *{
            margin: 0;
            padding: 0;
        }
        #wrap{
            display: flex;
            align-items: center;
            justify-content: center;
            width: 1000px;
            height: 700px;
            margin: 0 auto;
            border: 3px solid #e4e4e4;
            perspective: 400px; /*투시 주기*/
        }
        .container{
            animation: rotate 1s infinite alternate ease;
            /*이게 없으면 박스가 안돌아간다. */
            transform-style: preserve-3d;
        }
        @keyframes rotate{
            0%{
                transform: rotateY(0) rotateZ(0);
            }
            25%{
                transform: rotateX(180deg) rotateY(90deg);
            }
            100%{
                transform: rotateY(0) rotateX(90deg);
            }
        }
        .box {
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
            width: 200px;
            height: 200px;
            background: rgba(216, 112, 147, 0.5);
        }
        .back{
            transform: translateZ(-100px);    
        }
        .front{
            transform: translateZ(100px);
        }
        .bottom{
            transform: rotateX(90deg) translateZ(-100px);
            background: rgba(255, 208, 65, 0.5);
        }
        .top{
            transform: rotateX(90deg) translateZ(100px);
            background: rgba(79, 255, 15, 0.5);
        }
        .left{
            transform: rotateY(90deg) translateZ(-100px);
            background: rgba(63, 224, 249, 0.5);
        }
        .right{
            transform: rotateY(90deg) translateZ(100px);
            background: rgba(86, 51, 212, 0.5);
        }

    </style>

 

▲정육면체의 단면들을 감싸는 div 태그를 만들어 한 번 감싸줍니다.