javascripthtmlmodel-viewer

model-viewer and cursor moverment


I am using model-viewer for a 3D-Model and I want to move the 3D-Model according to cursor movement. I am not sure how I can connect the HTML variable in attribute "camera-controls" so that I can change them in js. So far I have written this in HTML:

<div class="hero">
 <model-viewer src="{% static "images/file_name.glb" %}" alt="3d model"
        loading="eager" camera-controls disable-zoom 
        reveal="auto" auto-rotate rotation-per-second="60deg"
        id="model">
 </model-viewer>
</div>

Solution

  • I managed to solve it with the following code:

    const modelViewer = document.getElementById('model'); 
    
    document.onmousemove = handleMouseMove;
        function handleMouseMove(event) {
            var eventDoc, doc, body;
    
            event = event || window.event; // IE-ism
    
            // If pageX/Y aren't available and clientX/Y are,
            // calculate pageX/Y - logic taken from jQuery.
            // (This is to support old IE)
            if (event.pageX == null && event.clientX != null) {
                eventDoc = (event.target && event.target.ownerDocument) || document;
                doc = eventDoc.documentElement;
                body = eventDoc.body;
    
                event.pageX = event.clientX +
                  (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
                  (doc && doc.clientLeft || body && body.clientLeft || 0);
                event.pageY = event.clientY +
                  (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
                  (doc && doc.clientTop  || body && body.clientTop  || 0 );
            }
    
            // Use event.pageX / event.pageY here
            x = - (event.pageX / window.innerWidth * 100 - 50)
            if(media_change.matches){
              x = - (event.pageX / window.innerWidth * 100 - 30)
            }
            y = - (event.pageY / window.innerHeight * 50) + 120
        }