Viewer API Part 1: Introduction

Back to overview

There’s a lot you can do with the Viewer API, but it can be a bit overwhelming at first glance, especially if you have no experience in JavaScript. I’m certainly no expert, but I’ll go through an introduction and a simple example to help get your feet wet.

Introduction

The Viewer API is a tool to programmatically load and manipulate an embedded Sketchfab model. Uses can be as simple as loading a model ‘on the fly’, or as complex as custom camera animations, manipulating objects in the scene, and syncing a viewer over the Internet.

Prepare your site

To use the API, you’ll need to insert it somewhere on your page. It should be downloaded or hotlinked. For example:

<script src="sketchfab-viewer-1.0.0.js"></script>

Then, you need an empty iframe. It has an id attribute, but no src attribute. You can add other attributes like height, width, and allowfullscreen.

<iframe src="" id="api-frame"></iframe>

 

Add your script

Add your empty iframe and the API link, as above.


<body>
  <p>This iframe was loaded by the Viewer API!</p>
  <!-- Your emptry iframe with some extra attributes -->
  <iframe src="" id="api-frame" allowfullscreen mozallowfullscreen="true" webkitallowfullscreen="true" width="400px" height="300px"></iframe>
  <!-- The API -->
  <script src="https://static.sketchfab.com/api/sketchfab-viewer-1.0.0.js"></script>

Declare some variables:

  • the iframe itself (document.getElementById())
  • API version number
  • ID of the model you want to load
  • Sketchfab API client object.

  <!-- Your new script -->
  <script type="text/javascript">
    // The iframe
    var iframe = document.getElementById( 'api-frame' );
    // API version
    var version = '1.0.0';
    // Model to load
    var urlid = 'e9e66978d4a248e2b0c4fdbb9912a573';
    // Sketchfab API client object
    var client = new Sketchfab( version, iframe );

Then, we’re ready to use the API. So, we initialize the API client, give it the model ID, and tell it to start immediately.


    // Initialize the API
    client.init( urlid, {
      // API is ready to use. You can interact with the viewer using the api object passed to the success function
      success: function onSuccess( api ){
        // Start the viewer immediately
        api.start();
      },
      // If initialization fails, throw an error
      error: function onError() {
        console.log( 'Viewer error' );
      }
    } );
  </script>
</body>

This is as simple as it gets. When the page loads, the API initializes and the model defined by urlid will be loaded in the iframe #api-frame. Obviously, this is pretty worthless because you can just embed a model as you normally would. Things get more interesting when you need to handle multiple models at once.

And here’s the result:

Build a model gallery

If you’re not familiar with our Playlists feature, check it out. It’s a great way to quickly embed a group of models. However, if you want to have a custom GUI and style, you can build it on top of the Viewer API. For this example, we’ll just have a few models and add a button to load each one.
First, the main HTML. It’s an empty iframe, just like before, plus 3 buttons. Note that each button has a unique id. They are wrapped up in some divs, just to make styling things easier later on. We also add the API like before.


<!-- Some divs to wrap the model iframes 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="blueButton">Blue</button>
            <button id="orangeButton">Orange</button>
            <button id="redButton">Red</button>
        </div>
    </div>
    <!-- The API -->
    <script src="https://static.sketchfab.com/api/sketchfab-viewer-1.0.0.js"></script>

Next, your JavaScript. This is very similar to the first example, but now we have three different model IDs. Then we declare three variables to represent the buttons (document.getElementById() again). I’m also declaring error and success here, instead of inside the initialization options. The effect is the same, but it’s a bit easier to read.


    <!-- Your new script -->
    <script>
        // Three models to load
        var blueModel = 'e9e66978d4a248e2b0c4fdbb9912a573',
            orangeModel = '6d87d624ddf94e08b4301115b6a2cb8f',
            redModel = '2853267156ba442985036e6e0d4288df',
            // Three buttons
            blueButton = document.getElementById( 'blueButton' ),
            orangeButton = document.getElementById( 'orangeButton' ),
            redButton = document.getElementById( 'redButton' ),
            // API version
            version = '1.0.0',
            // The iframe
            iframe = document.getElementById( 'api-frame' ),
            // Sketchfab API client object
            client = new Sketchfab( version, iframe ),
            // If initialization fails, throw an error
            error = function () {
                console.error( 'Sketchfab API Error!' );
            },
            // If initilization succeeds, start the model immediately
            success = function( api ) {
                api.start();
            };

Now, instead of simply initializing the API immediately, we create a function called loadModel that does the same thing. It takes two arguments, the client and a model urlid, and uses them to initialize the API. This way, we can re-use the function over and over again with different models. You can also add all kinds of embed options here, like Autospin, Autostart, hiding UI elements, etc.


        // A function to load a model
        function loadModel( client, urlid ) {
            console.log( 'loading a model' );
            client.init( urlid, {
                success: success,
                error: error,
                /* This is where you can add additional options like Autospin */
                autospin: 0.5
            });
        }

Finally, we need to tell the buttons to run the loadModel function when they are clicked. We do this with addEventListener().


        // Listen for click events on the buttons
        blueButton.addEventListener( 'click', function() {
            loadModel( client, blueModel );
        });
        orangeButton.addEventListener( 'click', function() {
            loadModel( client, orangeModel );
        });
        redButton.addEventListener( 'click', function() {
            loadModel( client, redModel );
        });
    </script>

And the result!

I’m using some CSS to define button styles and wrap everything with a maximum width. 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