Quickly create GUI for javascript variables with dat.GUI

1 minute read

I’m currently working on a book for Three.js. This book contains lots and lots of examples that show off the various features of this great library. I want readers of this book to experiment with the examples. I want them to see how changing variables change the output and animations. You could of course do this by editing the source code, and reloading the example, but that isn’t really that practical, especially when fine-tuning a specific example. I ran across dat.GUI a couple of months ago, which is a really useful, small library that you can use to change javascript variables from a simple GUI.

In this article I’ll quickly walk you through how to get started with library and as an example I’ll show you how you can use it to control animations in Three.js. I’ve added an example here, or just click on the image below:

Dat.GUI to control Three.png

The code to accomplish this is really easy to understand. First add the library:

<script type="text/javascript" src="libs/dat.gui.js"></script>

The next thing we need to configure is a javascript object that will hold the properties we want to change using data.GUI. In the main part of our javascript code we add the following javascript object.

       var controls = new function() {
            this.rotationSpeed = 0.02;
            this.bouncingSpeed = 0.03;

vascript object we define two properties: this.rotationSpeed and this.bouncingSpeed and their default value Next, we pass this object into a new dat.GUI object and define the range for these two properties.

        var gui = new dat.GUI();
        gui.add(controls, 'rotationSpeed',0,0.5);
        gui.add(controls, 'bouncingSpeed',0,0.5);

The rotationSpeed and bouncingSpeed properties are both set to a range of 0 to 0.5. All we need to do now is make sure that in our render loop we reference these two properties directly, so that when we make changes through the dat.GUI user interface it immediately affects the rotation and bounce speed of our objects.

function render() {
         cube.rotation.x += controls.rotationSpeed;
            cube.rotation.y += controls.rotationSpeed;
            cube.rotation.z += controls.rotationSpeed;
            sphere.position.x = 20+( 10*(Math.cos(step)));
            sphere.position.y = 2 +( 10*Math.abs(Math.sin(step)));

Now when you run this example you’ll see a simple user interface that you can use to control the bouncing and rotation speeds.