javascript3dblobmodel-viewer

Take a screenshot of modelviewer .glb file


I'm trying to take a screenshot of a .glb file displayed by model-viewer. But I can't arrive to a solution. I've read somewhere that the key is to convert the modelviewer to a blob object and then download an image.

<div class="button">
    <a id="download" href="#">Download button</a>
  </div>
  
<script>

function download() {
  const modelViewer =  document.querySelector("#modelviewertest");
  const screenshot = URL.createObjectURL(
      modelViewer.toBlob("image/jpeg")
    );
  const donwloadLink = document.querySelector("#download");
  donwloadLink.download = screenshot;
  donwloadLink.href = data;
}

I have tried to take a screenshot with html2canvas but not working. I would like to save into my server a screenshot of the glb model loaded on model-viewer.


Solution

  • There's a sample of taking a screenshot and downloading it here. The code is listed here in case the link goes down. Attribution goes to @milesgreen on GitHub, posted through this issue.

    const modelViewer = document.getElementById("viewer");
    
    async function downloadPosterToBlob() {
        const blob = await modelViewer.toBlob({ idealAspect: false });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "modelViewer_toBlob.png";
        a.click();
        URL.revokeObjectURL(url);
    }
    
    function downloadPosterToDataURL() {
        const url = modelViewer.toDataURL();
        const a = document.createElement("a");
        a.href = url;
        a.download = "modelViewer_toDataURL.png";
        a.click();
        URL.revokeObjectURL(url);
    }
    

    The JavaScript above references an HTML element that has an ID set to "viewer".

    <model-viewer id="viewer"
                  alt="Two cylinder engine"
                  src="models/2CylinderEngine.glb"
                  shadow-intensity="1"
                  camera-controls touch-action="pan-y">
    </model-viewer>
    

    Add a button in HTML and connect to its click event to trigger the download function above:

    document.querySelector("#download-button").addEventListener("click", downloadPosterToBlob);
    
    <button id="download-button">Download</button>
    

    Reference to the model-viewer web component's toBlob() method.