ReactJS에서 3D 큐브를 만드는 방법 🧊


이 게시물의 데모 저장소는 here에서 찾을 수 있습니다.


이 게시물과 함께 제공되는 Youtube 비디오를 찾을 수 있습니다here. 📺

목차


  • Introduction
  • Installation & Setup
  • Code
  • Customization

  • 소개

    Have you ever seen a 3D object rendered on a web page? Of course, you have, and chances are it was made using Javascript. But creating 3D objects with pure JavaScript requires a large amount of code, and might now always work in React environments. Not to say it isn't possible! However, with the implementation of react-3d-cube , you can easily add the 3D cube animation into any of your React applications.

    This tutorial was written to make you comfortable with react-3d-cube , but also to get you familiar with adjusting your code as needed.

    설치 및 설정

    Assuming you already have a React app made, install react-3d-cube .

    npm i react-3d-cube
    

    If it doesn't install on the first attempt, try adding on --legacy-peer-deps

    npm i react-3d-cube --legacy-peer-deps
    

    Then, create a new Cube folder, and inside add a Cube.js and Cube.css file.

    mkdir Cube
    cd Cube
    touch Cube.js
    touch Cube.css
    

    Open up both of your new files.

    open Cube.js
    open Cube.css
    

    Great job! Now it's time to fill those empty files with some code.

    암호

    Once you've opened up your Cube.js file, paste in the following template which can be found in the react-3d-cube 문서:

    import * as React from 'react';
    import './Cube.css'
    import Cube from 'react-3d-cube';
    
    class LogoCube extends React.Component {
      render() {
        return (
          <div>
            <center>
                <h1>react-3d-cube</h1>
                <h2>no children</h2>
                <div
                style={{
                    width: 300,
                    height: 300
                }}
                >
                <Cube size={300} index="front" />
                </div>
                <h2>set children</h2>
                <div
                style={{
                    width: 300,
                    height: 300
                }}
                >
                <Cube size={300} index="front">
                    <div>front</div>
                    <div>right</div>
                    <div>back</div>
                    <div>left</div>
                    <div>top</div>
                    <div>bottom</div>
                </Cube>
                </div>
            </center>
          </div>
        );
      }
    }
    export default LogoCube
    


    그런 다음 Cube.css 파일에 다음을 붙여넣습니다.

    * { box-sizing: border-box; }
    
    body { 
    font-family: sans-serif;
    margin: 10rem;
    }
    
    .scene {
      width: 200px;
      height: 200px;
      border: 1px solid #CCC;
      margin: 80px;
      perspective: 400px;
    }
    
    .cube {
      width: 200px;
      height: 200px;
      position: relative;
      transform-style: preserve-3d;
      transform: translateZ(-100px);
      transition: transform 1s;
    }
    
    .cube.show-front  { transform: translateZ(-100px) rotateY(   0deg); }
    .cube.show-right  { transform: translateZ(-100px) rotateY( -90deg); }
    .cube.show-back   { transform: translateZ(-100px) rotateY(-180deg); }
    .cube.show-left   { transform: translateZ(-100px) rotateY(  90deg); }
    .cube.show-top    { transform: translateZ(-100px) rotateX( -90deg); }
    .cube.show-bottom { transform: translateZ(-100px) rotateX(  90deg); }
    
    .cube__face {
      position: absolute;
      width: 200px;
      height: 200px;
      border: 2px solid black;
      line-height: 200px;
      font-size: 40px;
      font-weight: bold;
      color: white;
      text-align: center;
    }
    
    .cube__face--front  { background: hsla(  0, 100%, 50%, 0.7); }
    .cube__face--right  { background: hsla( 60, 100%, 50%, 0.7); }
    .cube__face--back   { background: hsla(120, 100%, 50%, 0.7); }
    .cube__face--left   { background: hsla(180, 100%, 50%, 0.7); }
    .cube__face--top    { background: hsla(240, 100%, 50%, 0.7); }
    .cube__face--bottom { background: hsla(300, 100%, 50%, 0.7); }
    
    .cube__face--front  { transform: rotateY(  0deg) translateZ(100px); }
    .cube__face--right  { transform: rotateY( 90deg) translateZ(100px); }
    .cube__face--back   { transform: rotateY(180deg) translateZ(100px); }
    .cube__face--left   { transform: rotateY(-90deg) translateZ(100px); }
    .cube__face--top    { transform: rotateX( 90deg) translateZ(100px); }
    .cube__face--bottom { transform: rotateX(-90deg) translateZ(100px); }
    
    label { margin-right: 10px; }
    


    이 두 파일 작성을 완료한 후 LogoCube.css 파일을 LogoCube.js 스크립트로 가져옵니다.

    import './LogoCube.css'
    


    그런 다음 애플리케이션에서 렌더링할 위치로 LogoCube.js를 가져올 수 있습니다.

    이 튜토리얼에서는 큐브를 빈 페이지로 렌더링하는 demo page을 만들었습니다. 큐브를 페이지에 렌더링하기 전에 큐브를 더 테스트하려면 react-router-dom를 사용하여 테스트 구성 요소에 연결하는 "테스트"경로를 만드는 것이 좋습니다.

    반응 앱을 시작하고 LogoCube.js가 렌더링되는 위치를 탐색하면 두 개의 큐브를 볼 수 있습니다. 이는 템플릿이 Cube가 하위 요소를 포함하거나 포함하지 않고 렌더링하는 방식을 보여주기 때문입니다. 또한 측면을 드래그하여 큐브를 자유롭게 뒤집을 수 있습니다!



    커스터마이징

    While your cubes look pretty cool, they still need some work. For starters, decided if you need two and if you don't, let's decide which one to delete. If you're looking for a plain cube with nothing on it, the first one with "no children" was made for you! However, if you want to add custom images, buttons, links, and more, you'll want to use the second cube with "set children".

    For this tutorial we will be moving forward with the "set children" cube, as the "no children" is more self-explanatory

    Your code should be shortened to:

    import * as React from 'react';
    import './Cube.css'
    import Cube from 'react-3d-cube';
    
    class LogoCube extends React.Component {
      render() {
        return (
          <div>
            <center>
                <h1>react-3d-cube</h1>
                <h2>set children</h2>
                <div
                style={{
                    width: 300,
                    height: 300
                }}
                >
                <Cube size={300} index="front">
                    <div>front</div>
                    <div>right</div>
                    <div>back</div>
                    <div>left</div>
                    <div>top</div>
                    <div>bottom</div>
                </Cube>
                </div>
            </center>
          </div>
        );
      }
    }
    export default LogoCube
    

    If you see only the transparent cube rendering, you did it correctly!

    It's time to start customizing your cube! Let's say you want to make a cube made of cat images, simply add in img tags as children elements to your cube side div :

    class LogoCube extends React.Component {
      render() {
        return (
        <center>
                <div>
                    <div
                        style={{
                            width: 300,
                            height: 300
                        }}
                    >
                    <Cube size={300} index="front">
                        <div >
                            <img style={{width: '280px', height: '300px'}} src="https://cdn.sanity.io/images/0vv8moc6/dvm360/0efdfab43ab36c3432ced2ceb2d52daae6a93c96-500x500.jpg"></img>
                        </div>
                        <div >
                            <img src="https://sitterforyourcritter.com/wp-content/uploads/2019/09/female-cat-1.jpg"></img>
                        </div>
                        <div >
                            <img src="https://pawsitivepotential.com/wp-content/uploads/2016/05/Tongue-Kitten-500x500_t.jpg"></img>
                        </div>
                        <div >
                            <img src="https://9ed48207422fa7fc5013-a6297eb5ec0f30e883355c8680f3b2d6.ssl.cf2.rackcdn.com/Hunter_wubba-9294%20(1)-20180803203739-20180803203910-500x500.jpg"></img>
                        </div>
                        <div >
                            <img src="https://www.guildinsurance.com.au/images/librariesprovider3/breed-images/500x500/cat_russian-blue-tica.jpg?sfvrsn=d16600b_2"></img>
                        </div>
                        <div >
                            <img src="https://www.catmospherecafe.com/assets/chiangmai-3ede22d062b60dde4a501695a2e0bfc7451f44d412ed68bd01cb6b44216270e4.jpg"></img>
                        </div>
                    </Cube>
                    </div>
                </div>
            </center>
    
    

    That code would render this cat-image cube:



    와우, 거의 최고에요! 🐱

    정육면체가 회전하는 것을 보거나 직접 해 보면 정육면체 면 사이의 이미지에 약간의 틈이 있음을 알 수 있습니다. 배경이 투명한 모든 이미지를 사용하는 경우 잠재적으로 멋진 효과를 만들 수 있지만 지금은 지저분해 보입니다. 일부 인라인 스타일을 사용하여 이러한 간격을 채우겠습니다.

    <Cube size={300} index="front">
                        <div style={{backgroundColor: 'black'}}>
                            <img style={{width: '280px', height: '300px'}} src="https://cdn.sanity.io/images/0vv8moc6/dvm360/0efdfab43ab36c3432ced2ceb2d52daae6a93c96-500x500.jpg"></img>
                        </div>
                        <div style={{backgroundColor: 'black'}}>
                            <img style={{width: '280px', height: '300px'}} src="https://sitterforyourcritter.com/wp-content/uploads/2019/09/female-cat-1.jpg"></img>
                        </div>
                        <div style={{backgroundColor: 'black'}}>
                            <img style={{width: '280px', height: '300px'}} src="https://pawsitivepotential.com/wp-content/uploads/2016/05/Tongue-Kitten-500x500_t.jpg"></img>
                        </div>
                        <div style={{backgroundColor: 'black'}}>
                        <img style={{width: '280px', height: '300px'}} src="https://9ed48207422fa7fc5013-a6297eb5ec0f30e883355c8680f3b2d6.ssl.cf2.rackcdn.com/Hunter_wubba-9294%20(1)-20180803203739-20180803203910-500x500.jpg"></img>
                        </div>
                        <div style={{backgroundColor: 'black'}}>
                        <img style={{width: '280px', height: '300px'}} src="https://www.guildinsurance.com.au/images/librariesprovider3/breed-images/500x500/cat_russian-blue-tica.jpg?sfvrsn=d16600b_2"></img>
                        </div>
                        <div style={{backgroundColor: 'black'}}>
                        <img style={{width: '280px', height: '300px'}} src="https://www.catmospherecafe.com/assets/chiangmai-3ede22d062b60dde4a501695a2e0bfc7451f44d412ed68bd01cb6b44216270e4.jpg"></img>
                        </div>
                    </Cube>
    


    이제 큐브가 다음과 같이 렌더링됩니다.



    🐾 Pawsitively 놀라운! 좋아, 이제 끝났어.

    이것이 React에서 3D 큐브를 생성하는 거의 모든 것입니다. 이 큐브는 이미지만 표시하지만 버튼, 링크 등을 추가할 수 있습니다. 원하는 만큼 창의력을 발휘하세요! 진심으로 이 기사가 도움이 되었기를 바라며 피드백을 주시면 감사하겠습니다.

    좋은 웹페이지 즐겨찾기