javascriptmodel-viewer

how rotate model with code in modelviewer?


I create a model-view tag and load 3d gltf object.

Now I am going to rotate it with mouse move. How can I do this? My code:

        <style>
            body {
                background-color: rgba(255, 255, 255, 0.5);
            }
            #model {
                width: 500px;
                height: 500px;
            }
        </style>
    </head>
    <body>
        <script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script>
            <model-viewer camera-orbit="0deg 0deg" class="a" id="model"   orientation="45deg 45deg 0" auto-rotate src="static/models/scene.gltf" loading="eager"></model-viewer><script>
            document.addEventListener('mousemove', parallax);
            function parallax (e) {
                this.querySelectorAll('#model').forEach(layer => {
                    const speed = 2;
                    const x = (window.innerWidth - e.pageX*speed)/100
                    const y = (window.innerHeight - e.pageY*speed)/100
    
                    layer.style.transform = `translateX(${x}px) translateY(${y}px)`
                });
            }
            
        </script>
    </body>

Solution

  • As far as I know, you should add 'camera-controls' in your code to the body-section.

    In this example:

    <body>
      <model-viewer src="static/models/scene.gltf" camera-controls ></model-viewer>
    </body>