Spline API: Real-Time 3D Model Toggle Tutorial

Home 3D Spline API: Real-Time 3D Model Toggle Tutorial

April 23, 2024

In this Spline tutorial I will show you how to use the Spline API to toggle between 3D models in real time.

Note: Timestamps 11:35 & 17:37 Use the variable name not the 3D Model layer name.

Timestamps:

  • 0:00 Spline Tutorial Introduction
  • 0:44 Setup Spline Scene
  • 4:00 Create Spline Variables
  • 8:23 Export Spline Scene
  • 8:47 Spline Code Explained
  • 10:42 Example 1: Toggle Photos
  • 12:38 Example 2: Toggle 3D Chairs
  • 14:00 Example 3: Change Carpet Sides
  • 15:06 Add Buttons
  • 15:49 Fix Jumping Button Links

JavaScript Code

				
					<canvas id="canvas3d"></canvas>
<script type="module">
   import { Application } from 'https://unpkg.com/@splinetool/runtime@1.0.93/build/runtime.js';

   const canvas = document.getElementById('canvas3d');
   const spline = new Application(canvas);

   spline.load('scene.splinecode')
       .then(() => {
           const button1 = document.getElementById('button1');
           button1.addEventListener('click', () => {
              // Toggle values directly
              spline.setVariables({ 
                  photo1: spline.getVariable('photo1') === 0 ? 1 : 0, 
                  photo2: spline.getVariable('photo2') === 0 ? 1 : 0 
              });
           });
		   
		   const button2 = document.getElementById('button2');
           button2.addEventListener('click', () => {
              // Toggle values directly
              spline.setVariables({ 
                  chair1: spline.getVariable('chair1') === 0 ? 1.39 : 0, 
                  chair2: spline.getVariable('chair2') === 0 ? 2.85 : 0 
              });
           });
		   
		   const button3 = document.getElementById('button3');
           button3.addEventListener('click', () => {
              // Toggle values directly
              spline.setVariables({ 
                  carpet: spline.getVariable('carpet') === 40 ? 6 : 40
              });
           });
       });
       var buttons = document.querySelectorAll('#button1, #button2, #button3');

    // Add a click event listener to each button
    buttons.forEach(function(button) {
        button.addEventListener('click', function(event) {
            // Prevent the default behavior of the button
            event.preventDefault();
        });
    });
</script>
				
			

*Some of the links on this page are affiliate links, meaning we may receive a commission if you follow them. This allows us to continue providing free content and educational resources for you. Thank you for supporting our small business!

More Free Resources