Graphical interface for controlling javascript applications in real time

DAT.gui makes it easy to manipulate almost anything in javascript via some basic controls

dat.gui,javascript,d3.js,three.js,processing.js,GUI

08/09/2012

I've been playing around with several visual javascript libraries lately, among them processing.js, three.js, and d3.js - and often found myself wishing I had an easy way to allow a user to control the appearance of things on screen simply, without me having to build custom interface elements. I found a great tool to accomplish this: dat.GUI.

Simply by passing a property of an object to dat.GUI, it will build a box with that property's name, and the appropriate control to manipulate the property's value, changing things on screen in real time. If the property is a number, it will build a slider. If it is a string, it will include a text box. If it is an array, it will include a dropdown. Boolean - checkbox, color value - color slider! Plus it allows you to constrain the values to a minimum and maximum, and increase them at certain steps if you desire. I found the documentation a little confusing for dat.gui though, so I figured I'd post a simple example on how to set things up.

First, of course, download the source, place it in the appropriate directory relative to your code, and include it in your html page:

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

Then, in your javascript that you want to control your site, create an object that will contain all the variables you want to be able to change:

var configObj = {};

We'll add a simple numerical property to this object, which will be interpreted by dat.gui with a slider:

var configObj = {"Amount" : .5 };

Here we're creating a property called Amount, with a value of .5, which will create a title "Amount" in the GUI, with a slider set at 50% of its full value. Now, we need to instantiate the GUI, and add the "Amount" control:


var gui = new dat.GUI();
var amountChanger = gui.add(configObj,"Amount", 0, 1);

Here, we're creating a variable called amountChanger, which tells the gui to add a slider that will control the "Amount' property with in our configObj object. We're giving at a minimum of 0, and a maximum of 1. If you were to run your code, you should see the GUI in the upper right of your browser window, with the title and slider for the property you created. When you move it, you may notice that while the slider value is changing, nothing is changing within your code. If that's the case, just set up a function that detects when the slider is being changed, and passes it's variable on to whatever function you need to tie it to. In this case, let's say our GUI will control the opacity of any div on the screen (we'll use jQuery to make it easy):


amountChanger.onChange(function(value) {
  $('div').css({"opacity" : value });
});

That's all there is to it - now slide the slider, and all of your divs should change in opacity!