{"id":119941165409,"date":"2015-05-26T08:02:38","date_gmt":"2015-05-26T15:02:38","guid":{"rendered":"http:\/\/blog.sketchfab.com\/post\/119941165409"},"modified":"2018-12-12T21:17:00","modified_gmt":"2018-12-12T20:17:00","slug":"viewer-api-part-1-introduction","status":"publish","type":"post","link":"https:\/\/sketchfab.com\/blogs\/community\/viewer-api-part-1-introduction\/","title":{"rendered":"Viewer API Part 1: Introduction"},"content":{"rendered":"<p>There\u2019s a lot you can do with the <a href=\"https:\/\/sketchfab.com\/developers\/viewer\" target=\"_blank\">Viewer API<\/a>, but it can be a bit overwhelming at first glance, especially if you have no experience in JavaScript. I\u2019m certainly no expert, but I\u2019ll go through an introduction and a simple example to help get your feet wet.<\/p>\n<h3>Introduction<\/h3>\n<p>The Viewer API is a tool to programmatically load and manipulate an embedded Sketchfab model. Uses can be as simple as loading a model \u2018on the fly\u2019, or as complex as <a href=\"https:\/\/sketchfab.com\/developers\/viewer\/customanimation\" target=\"_blank\">custom camera animations<\/a>, <a href=\"https:\/\/labs.sketchfab.com\/experiments\/configurator\/\" target=\"_blank\">manipulating objects in the scene<\/a>, and <a href=\"https:\/\/labs.sketchfab.com\/experiments\/viewer-sharing\/\" target=\"_blank\">syncing a viewer over the Internet<\/a>.<\/p>\n<h3>Prepare your site<\/h3>\n<p>To use the API, you\u2019ll need to insert it somewhere on your page. It should be downloaded or <a href=\"https:\/\/en.wikipedia.org\/wiki\/Inline_linking\" target=\"_blank\" rel=\"nofollow\">hotlinked<\/a>. For example:<\/p>\n<pre><code>&lt;script src=\"sketchfab-viewer-1.0.0.js\"&gt;&lt;\/script&gt;<\/code><\/pre>\n<p>Then, you need an empty iframe. It has an <strong>id<\/strong> attribute, but no <strong>src<\/strong> attribute. You can add other attributes like height, width, and allowfullscreen.<\/p>\n<pre><code>&lt;iframe src=\"\" id=\"api-frame\"&gt;&lt;\/iframe&gt;<\/code><\/pre>\n<p>&nbsp;<\/p>\n<h3>Add your script<\/h3>\n<p>Add your empty iframe and the API link, as above.<\/p>\n<pre><code>\r\n&lt;body&gt;\r\n  &lt;p&gt;This iframe was loaded by the Viewer API!&lt;\/p&gt;\r\n  &lt;!-- Your emptry iframe with some extra attributes --&gt;\r\n  &lt;iframe src=\"\" id=\"api-frame\" allowfullscreen mozallowfullscreen=\"true\" webkitallowfullscreen=\"true\" width=\"400px\" height=\"300px\"&gt;&lt;\/iframe&gt;\r\n  &lt;!-- The API --&gt;\r\n  &lt;script src=\"https:\/\/static.sketchfab.com\/api\/sketchfab-viewer-1.0.0.js\"&gt;&lt;\/script&gt;<\/code><\/pre>\n<p>Declare some variables:<\/p>\n<ul>\n<li>the iframe itself (<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document\/getElementById\" target=\"_blank\" rel=\"nofollow\"><strong>document.getElementById()<\/strong><\/a>)<\/li>\n<li>API version number<\/li>\n<li>ID of the model you want to load<\/li>\n<li>Sketchfab API <strong>client<\/strong> object.<\/li>\n<\/ul>\n<pre><code>\r\n  &lt;!-- Your new script --&gt;\r\n  &lt;script type=\"text\/javascript\"&gt;\r\n    \/\/ The iframe\r\n    var iframe = document.getElementById( 'api-frame' );\r\n    \/\/ API version\r\n    var version = '1.0.0';\r\n    \/\/ Model to load\r\n    var urlid = 'e9e66978d4a248e2b0c4fdbb9912a573';\r\n    \/\/ Sketchfab API client object\r\n    var client = new Sketchfab( version, iframe );<\/code><\/pre>\n<p>Then, we\u2019re ready to use the API. So, we initialize the API client, give it the model ID, and tell it to start immediately.<\/p>\n<pre><code>\r\n    \/\/ Initialize the API\r\n    client.init( urlid, {\r\n      \/\/ API is ready to use. You can interact with the viewer using the api object passed to the success function\r\n      success: function onSuccess( api ){\r\n        \/\/ Start the viewer immediately\r\n        api.start();\r\n      },\r\n      \/\/ If initialization fails, throw an error\r\n      error: function onError() {\r\n        console.log( 'Viewer error' );\r\n      }\r\n    } );\r\n  &lt;\/script&gt;\r\n&lt;\/body&gt;<\/code><\/pre>\n<p>This is as simple as it gets. When the page loads, the API initializes and the model defined by <strong>urlid<\/strong> will be loaded in the iframe <strong>#api-frame<\/strong>. Obviously, this is pretty worthless because you can just <a href=\"https:\/\/help.sketchfab.com\/hc\/en-us\/articles\/203509907-Share-Models\">embed a model<\/a> as you normally would. Things get more interesting when you need to handle multiple models at once.<\/p>\n<p>And here\u2019s the result:<\/p>\n<div class=\"oembed-sketchfab-com\"><iframe src=\"https:\/\/blog.sketchfab.com\/wp-content\/uploads\/2015\/05\/index.html\" width=\"300\" height=\"150\"><\/iframe><\/div>\n<h3>Build a model gallery<\/h3>\n<p>If you\u2019re not familiar with our Playlists feature, <a href=\"https:\/\/help.sketchfab.com\/hc\/en-us\/articles\/203821409\" target=\"_blank\">check it out<\/a>. It\u2019s 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\u2019ll just have a few models and add a button to load each one.<br \/>\nFirst, the main HTML. It\u2019s an empty iframe, just like before, plus 3 buttons. Note that each button has a unique <strong>id<\/strong>. They are wrapped up in some <strong>divs<\/strong>, just to make styling things easier later on. We also add the API like before.<\/p>\n<pre><code>\r\n&lt;!-- Some divs to wrap the model iframes and three buttons --&gt;\r\n&lt;body&gt;\r\n    &lt;div class=\"wrapper\"&gt;\r\n        &lt;iframe src=\"\" id=\"api-frame\" allowfullscreen mozallowfullscreen=\"true\" webkitallowfullscreen=\"true\" width=\"400px\" height=\"300px\"&gt;&lt;\/iframe&gt;\r\n        &lt;div class=\"buttons\"&gt;\r\n            &lt;button id=\"blueButton\"&gt;Blue&lt;\/button&gt;\r\n            &lt;button id=\"orangeButton\"&gt;Orange&lt;\/button&gt;\r\n            &lt;button id=\"redButton\"&gt;Red&lt;\/button&gt;\r\n        &lt;\/div&gt;\r\n    &lt;\/div&gt;\r\n    &lt;!-- The API --&gt;\r\n    &lt;script src=\"https:\/\/static.sketchfab.com\/api\/sketchfab-viewer-1.0.0.js\"&gt;&lt;\/script&gt;<\/code><\/pre>\n<p>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 (<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document\/getElementById\" target=\"_blank\" rel=\"nofollow\"><strong>document.getElementById()<\/strong><\/a> again). I\u2019m also declaring <strong>error<\/strong> and <strong>success<\/strong> here, instead of inside the initialization options. The effect is the same, but it\u2019s a bit easier to read.<\/p>\n<pre><code>\r\n    &lt;!-- Your new script --&gt;\r\n    &lt;script&gt;\r\n        \/\/ Three models to load\r\n        var blueModel = 'e9e66978d4a248e2b0c4fdbb9912a573',\r\n            orangeModel = '6d87d624ddf94e08b4301115b6a2cb8f',\r\n            redModel = '2853267156ba442985036e6e0d4288df',\r\n            \/\/ Three buttons\r\n            blueButton = document.getElementById( 'blueButton' ),\r\n            orangeButton = document.getElementById( 'orangeButton' ),\r\n            redButton = document.getElementById( 'redButton' ),\r\n            \/\/ API version\r\n            version = '1.0.0',\r\n            \/\/ The iframe\r\n            iframe = document.getElementById( 'api-frame' ),\r\n            \/\/ Sketchfab API client object\r\n            client = new Sketchfab( version, iframe ),\r\n            \/\/ If initialization fails, throw an error\r\n            error = function () {\r\n                console.error( 'Sketchfab API Error!' );\r\n            },\r\n            \/\/ If initilization succeeds, start the model immediately\r\n            success = function( api ) {\r\n                api.start();\r\n            };<\/code><\/pre>\n<p>Now, instead of simply initializing the API immediately, we create a function called <strong>loadModel<\/strong> that does the same thing. It takes two arguments, the <strong>client<\/strong> and a model <strong>urlid<\/strong>, 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 <a href=\"https:\/\/help.sketchfab.com\/hc\/en-us\/articles\/203509907-Share-Models#embed-options\" target=\"_blank\">embed options<\/a> here, like Autospin, Autostart, hiding UI elements, etc.<\/p>\n<pre><code>\r\n        \/\/ A function to load a model\r\n        function loadModel( client, urlid ) {\r\n            console.log( 'loading a model' );\r\n            client.init( urlid, {\r\n                success: success,\r\n                error: error,\r\n                \/* This is where you can add additional options like Autospin *\/\r\n                autospin: 0.5\r\n            });\r\n        }<\/code><\/pre>\n<p>Finally, we need to tell the buttons to run the <strong>loadModel<\/strong> function when they are clicked. We do this with <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/EventTarget\/addEventListener\" target=\"_blank\" rel=\"nofollow\"><strong>addEventListener()<\/strong><\/a>.<\/p>\n<pre><code>\r\n        \/\/ Listen for click events on the buttons\r\n        blueButton.addEventListener( 'click', function() {\r\n            loadModel( client, blueModel );\r\n        });\r\n        orangeButton.addEventListener( 'click', function() {\r\n            loadModel( client, orangeModel );\r\n        });\r\n        redButton.addEventListener( 'click', function() {\r\n            loadModel( client, redModel );\r\n        });\r\n    &lt;\/script&gt;<\/code><\/pre>\n<p>And the result!<\/p>\n<div class=\"oembed-sketchfab-com\"><iframe src=\"https:\/\/blog.sketchfab.com\/wp-content\/uploads\/2015\/05\/colors.html\" width=\"300\" height=\"150\"><\/iframe><\/div>\n<p>I\u2019m using some CSS to define button styles and wrap everything with a maximum width. You can get the whole HTML file for this example <a href=\"https:\/\/blog.sketchfab.com\/wp-content\/uploads\/2015\/05\/colors.html\" target=\"_blank\">here<\/a>. I hope it will be helpful for someone! :)<\/p>\n<p><em>Edit: A small note to WordPress users. WP automatically wraps new HTML lines in &lt;p&gt; tags. This will quickly break inline JavaScript as it\u2019s used above. You should <a href=\"https:\/\/en.wikipedia.org\/wiki\/Inline_linking\" target=\"_blank\" rel=\"nofollow\">hotlink<\/a> your script, which isn\u2019t a bad idea in general, either.<\/em><\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There\u2019s a lot you can do with the Viewer API, but it can be a bit overwhelming at first glance, especially if you have no<\/p>\n","protected":false},"author":8,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[617],"tags":[35],"class_list":["post-119941165409","post","type-post","status-publish","format-standard","hentry","category-api-spotlight","tag-api"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/posts\/119941165409","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/comments?post=119941165409"}],"version-history":[{"count":9,"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/posts\/119941165409\/revisions"}],"predecessor-version":[{"id":142059986938,"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/posts\/119941165409\/revisions\/142059986938"}],"wp:attachment":[{"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/media?parent=119941165409"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/categories?post=119941165409"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sketchfab.com\/blogs\/community\/wp-json\/wp\/v2\/tags?post=119941165409"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}