February 12, 2021

More on screenshots

We have quite a few articles on using getScreenShot() function of the Viewer in order to generate a picture of the model, e.g.:
Get Base64 Encode String of Screenshot with Markups
Screenshot automation of 2D Drawings with Forge Viewer and Headless Chrome

That function is not for taking a picture of a specified area of the Viewer, but taking a picture of the Viewer as if it was the given size.
So if my Viewer is currently 400x400px and I call getScreenShot(200, 400), then it's like changing the Viewer element's size to 200x400px, calling viewer.resize(), and then taking a screenshot of it.

This also means that you can create a better quality picture than the one the user is seeing - I can e.g. create a 1600x900px screenshot no matter what the size of the Viewer currently is. 

When resizing the Viewer it will always cover the same vertical area of the model - see picture on top.

If you want to get a picture of a section of the Viewer, then getScreenShot() won't work for all scenarios:

Using getScreenShot() to generate picture of a section
For that, it would be much more reliable to use getScreenShot() with values that match the aspect ratio of the Viewer element and then use some JavaScript functions to crop the image to whatever section you need.  

E.g. if you just added a canvas object like this to your web page ...

<canvas id="MyCanvas"></canvas>

... then you could use this code to fill it with a given middle section of the Viewer:

function crop(viewer, w, h) {
    let vw = viewer.container.clientWidth;
    let vh = viewer.container.clientHeight;

    if (w > vw || h > vh) {
        alert("Dimensions should not be larger than Viewer");
        return;
    }

    viewer.getScreenShot(vw, vh, blob => {
        var canvas = document.getElementById('MyCanvas');
        var ctx = canvas.getContext('2d');
        canvas.width = w;
        canvas.height = h;
        var image = new Image();
        image.onload = () => {
            ctx.clearRect(0, 0, w, h);
            let sx = (vw - w) / 2;
            let sy = (vh - h) / 2;
            ctx.drawImage(image, sx, sy, w, h, 0, 0, w, h);
        }
        image.src = blob;
    });
}

If I call it like this ...

crop(viewer, 400, 200)

... then I get this result

Crop Viewer screenshot

By the way, there is also another way to take a screenshot: Autodesk.Viewing.ScreenShot.getScreenShot(..)
This provides many more options. For details, the best thing is to just check the source code of viewer3D.js - search for getScreenShot(w, h, onFinished, options, viewerImpl)

 

Related Posts