Learn to code with the Sketchfab Viewer API. Part 2: Controlling the Camera

Back to overview

This is the second installment of a Viewer API tutorial series. If you’re new to the Viewer API (and/or JavaScript in general), go read Part 1! In this post, I’ll be introducing the setCameraLookAt function, which lets you set a position and target for the camera. You can use this method to do awesome stuff like custom camera animations or walkthroughs, sync web page content to Sketchfab Annotations, and collaborate on a model over the Internet. This example will be much simpler. We’ll load a model, define two camera positions, and add some buttons to switch between them.

setCameraLookAt

setCameraLookAt (or just lookAt) takes 2 required arguments and 2 optional arguments:

setCameraLookAt( eye, target, [duration], [callback] )

eye is the position of the camera or eye. It should be coordinates formatted like

[ x, y, z ]

target is the position to look at, also coordinates

[ x, y, z ]

For the purposes of this post, we won’t worry about duration and callback.

Prepare your site

Just like in Part 1, we’ll need the API, an empty iframe, and some buttons with ids on your page.


<!-- A div to wrap the model iframe and three buttons -->
<body>
    <div class="wrapper">
        <iframe src="" id="api-frame" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" width="400px" height="300px"></iframe>
        <div class="buttons">
            <button id="start">Start</button>
            <button id="left">Left</button>
            <button id="right">Right</button>
        </div>
    </div>

    <!-- The API -->
    <script src="https://static.sketchfab.com/statics/api/sketchfab-viewer-1.0.0.js"></script>

Add your script

Next, we write some new code. Here come our variables:


    <!-- Your new script -->
    <script>
        // Model
        var model = 'f5427bf0d62449f2943fc904a1ae082a',

            // Two buttons
            startButton = document.getElementById( 'start' ),
            leftButton = document.getElementById( 'left' ),
            rightButton = document.getElementById( 'right' ),

            // API version
            version = '1.0.0',

            // The iframe
            iframe = document.getElementById( 'api-frame' ),

            // The API client object
            client = new Sketchfab( version, iframe ),

            // The API object, declared globally so we can use it anywhere
            api,

            // Camera
            target = [ 0.0, 0.0, 32 ],
            cameraLeft = [ 120, 0, 32 ],
            cameraRight = [ -120, 0, 32 ],

            // Defining error and success outside initialization, for easy reading
            error = function () {
                console.error( 'Sketchfab API Error!' );
            },

            // If initilization succeeds, start the model immediately
            success = function( callback ) {
                api = callback;
                api.start();
            };

A lot of the basic API initialization steps will be the same as last time. You can see the ID of the model we want to load, our 3 buttons, the API version, the empty iframe, then the client and API object. Note that we’re declaring an empty api object. We need to access it globally, but it won’t actually be defined until we initialize the API. This happens in the success function: define the api object as the initialization callback, then start it.

The new stuff here is the Camera section. Exact coordinates will depend on the model and what you want to view. At the moment, Sketchfab has no real scale, so coordinates are just a generic unit. In this case, I want the target to be slightly above the scene origin, so X is 0, Y is 0, and Z is 32. I chose 32 through trial and error. We want a right-side view and a left-side view, so I’m just moving the camera position along the X-axis.

Lastly, we create functions (and attach them to the buttons).


        // A function to load a model
        function loadModel( client, urlid ) {
            console.log( 'loading a model' );
            client.init( urlid, {
                success: success,
                error: error
            });
        }

        // Listen for click events on the buttons
        startButton.addEventListener( 'click', function() {
            loadModel( client, model );
        });

        leftButton.addEventListener( 'click', function() {
            api.setCameraLookAt( cameraLeft, target );
        });

        rightButton.addEventListener( 'click', function() {
            api.setCameraLookAt( cameraRight, target );
        });
</script>

The loadModel function is the same as last time, and added the to start button. Remember, this is where you can add embed parameters like autospin. And finally, the setCameraLookAt method appears! We just match up the button and camera position.

And the result!

Just like last time, there’s a bit of CSS used on the buttons and iframe. You can get the whole HTML file for this example here. I hope it will be helpful for someone! 🙂

Edit: A small note to WordPress users. WP automatically wraps new HTML lines in <p> tags. This will quickly break inline JavaScript as it’s used above. You should hotlink your script, which isn’t a bad idea in general, either.

 

About the author

James Green

Sketchfab Product Specialist & Support King | Beer Enthusiast | Pokémon Master


Leave a Reply

Your email address will not be published. Required fields are marked *

Related articles