360도 보기 - HTML5 및 JS

14295 단어


360도 뷰를 만들어 보았습니다. 코드는 다음과 같습니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>360 Degree View</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        html, body {
            width: 100vw;
            height: 100vh;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        img {
            width: 100%;
        }

        .container {
            width: 80%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: move;
        }
    </style>
</head>
<body>
    <div id="carContainer" class="container">
    </div>

    <script>
        const carContainer = document.getElementById('carContainer');
        // Car 360 degree view consists 24 images.
        const IMAGE_COUNT = 24;
        const images = [];
        // Mousedown
        var hold = false;
        // Mouse X position relative to the container div
        var posX = 0;

        createImages();
        fillContainerWithImages();

        // Create 24 images and push to images array
        // All the images except one should be invisible
        function createImages() {
            for (let i=0; i<IMAGE_COUNT; i++) {
                const img = document.createElement('img');
                img.src = `img/${i + 1}.webp`;
                img.alt = '';
                img.draggable = false;

                if (i > 0)
                    img.style.display = 'none';

                images.push(img);
            }
        }        

        function fillContainerWithImages() {
            images.forEach(i => carContainer.appendChild(i));
        }

        carContainer.addEventListener('mousedown', function(event) {
            hold = true;
        });

        carContainer.addEventListener('mouseup', function(event) {
            hold = false;
        });

        carContainer.addEventListener('mousemove', function(event) {
            if (hold) {
                // Mouse x position on container
                posX = Math.abs(
                       (document.body.clientWidth - carContainer.getBoundingClientRect().width)
                       / 2 - event.clientX);
                // Container width / 24
                const piece = carContainer.getBoundingClientRect().width / IMAGE_COUNT;
                // Make invisible all images
                images.forEach(i => i.style.display = 'none');
                // Make visible one image
                images[Math.floor(posX / piece)].style.display = 'block';
            }
        });
    </script>
</body>
</html>

좋은 웹페이지 즐겨찾기