nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: Vanilla JavaScript

Brendan Eichs baby, JavaScript what was once considered evil has finally matured into a very useful language.

dat.gui – controller library for JavaScript

Very recently I’ve been looking at some awesome JavaScript experiments and have noticed they are all using the same GUI. Now I fully admit I had a little ‘blonde’ moment as I assumed it was just a style everyone had adopted; developers being ‘one of the cool kids’, that type of thing. It turns out I was wrong, and it finally clicked. All the experiments have started using a little controller library called dat.gui.

After it appeared on Google’s workshop (along with three.js), I thought it was about time I had a play with this neat little library. Luckily there’s an excellent set of documentation and working examples available so you can dive right in. Here’s a code example of how to get started:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//Define the controller function
var FresnelControls = function() {
    this.movingParticles = 5000;
    this.seedColor = "#ff0098";
};

//Create the Dat.gui controls
var fc = new FresnelControls();

//Create the GUI
var gui = new dat.GUI();

//Add 2 folders
var f1 = gui.addFolder('Particle Dynamics');
var f2 = gui.addFolder('Particle Colours');
       
//Add the moving particles controller to folder 1
f1.add(fc, 'movingParticles', 0, 5000).step(1);

//Add the colour controller, store in a var to attach events
var seedColor = f2.addColor(fc, 'seedColor');

//Colour change event
seedColor.onChange(function(value) {
    //Do something on color change...
});

I decided to dig out an old demo I created last year and adapt it to use dat.gui. Originally I used jQuery + jQuery UI to control the JavaScript variables. It worked well, but it really added page weight (jQuery + UI came to over 90Kb); not great when you are only using it for the sliders.

Following the documentation you start off simple and progressively add more of the dat.gui functionality. You can see my adapted demo here. The dat.gui code is highlighted if you want to see how it was set up.

Dat.gui in action on the Euler Spiral demo I created.

You can see dat.gui in action on my modified Euler Spiral demo.

Dat.gui really has some excellent features available. I was able to make use of the colour picker, presets and folder functionality; but there’s a whole host of others I didn’t, such as the custom placement and updating the display automatically. Personally I love the presets functionality; supply the GUI with a little bit of JSON and away you go!

As always, a big thank you goes out to the Data Arts Team in Google’s Creative Lab for creating such a useful little library! One I will be using in every demo I create from now on.

A little bit of MicroJS

Recently there was a flurry of talk around a little something called MicroJS, mainly thanks to a website of the same name created by Thomas Fuchs, author of the script.aculo.us user interface library. I’m not sure if Thomas coined the term “MicroJS” or if it’s been in use for a while, but it describes the micro-framework methodology perfectly. So what is a micro-framework? The best way to answer that is to first ask what is a JavaScript framework?

JavaScript frameworks have been around since around 2005 (looking at the Prototype and jQuery history); their purpose is to allow developers to easily add interactivity to a page by creating a JavaScript abstraction layer to build from. The library takes care of any cross browser issues and quirks, allowing developers to focus on the “cool” stuff, building websites. As a developer I can’t thank all the library authors enough; without them my working life would be so much more stressful (and my hair would be even grayer than it is now!).

Once you know what a JavaScript framework is, it doesn’t take a genius to guess what a micro-framework is. Where as a full framework will have many tools (methods) a developer can use, a micro-framework only focuses on a very specific set of functions. I like the knife analogy: a full-framework like Dojo would be a Swiss Army knife where as a micro-framework could be considered a small pen knife. So which do you use in a project? This completely depends on the project in hand. I’ve put together a small list of pros and cons for each (let me know if you have any others):

Full Framework

  • Pros
  • Extensive set of features to cater for most eventualities.
  • Consistent API across features.
  • Large user base with lots of community support.
  • Huge number of working examples available.
  • Many developers to fix bugs and add additional functionality.
  • Single point of reference of documentation.
  • Cons
  • Large code base could be very daunting to new users.
  • Large page footprint.
  • Many features of the library may not be needed.

Micro-Framework

  • Pros
  • Small page weight, usually less than 5K.
  • Small set of features so very quick to pick up and use.
  • Main focus on a very specific set of functionality.
  • No feature creep or excess code.
  • Use the right tool for the right job.
  • Cons
  • Small number of developers, bugs and issues may take a while to be fixed.
  • Development of the framework may stop completely.
  • May be very little support from the author and the community.
  • Fellow developers in your team may not be familiar with the framework.
  • Mixing micro-frameworks could conflict if badly coded.
  • Multiple frameworks could mean multiple HTTP requests.
  • Multiple points of reference for API docs.
  • Multiple frameworks could lead to an overlap in functionality.

Many of the cons for micro-frameworks stem from using more than one at a time, but if you only plan on using one then they can be ignored.

Micro-frameworks caught my eye recently due to a couple of small projects I’d been working on. The projects all used vanilla JavaScript as there was no need for a helper library. I later realised I needed to attach a few events and manipulate the DOM but I wanted to avoid including jQuery in the project as I only needed a small fraction of its functionality. Luckily the MicroJS website came to the rescue.

The examples below are taken from Query, Bonzo, Events.js and Bean. As you can see the usage for each is pretty self-explanatory with lots more functionality is available from each library’s website. If you’re a jQuery user the syntax will look very familiar.

CSS selector and DOM utility

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
Query - Dustin Diaz
https://github.com/ded/qwery
CSS selector engine
*/

query("#myid");
query(".myclass");
query("#myid .myclass div a");
query("a, div, strong");

/*
Query Paired with Bonzo - Dustin Diaz
https://github.com/ded/bonzo
DOM utility
*/

query("#myid").show();
query(".myclass").offset(50, 100);
query("#myid .myclass div a").addClass("anchorClass");
query("a, div, strong").remove();

Events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
Events.js - James Brumond
https://github.com/kbjr/Events.js
Event handler library
*/

Events.bind(window, 'load', function(e) {
    //Page loaded, do something
});
//Invoke the page load event
Events.invoke(window, 'load');
//Mouse click event
Events.bind(selectedElements, 'click', function(e) {
    //Mouse has been clicked
});
//Very handy keystroke event
Events.bind(document, 'keystroke.Ctrl+Shift+Alt+S', function(e) {
    saveMySlices();
});

/*
Bean - Dustin Diaz
https://github.com/fat/bean
Event handler library
*/

bean.add(selectedElements, 'click', function (e) {
    //Mouse has been clicked
});
//DOM has loaded
bean.add(document, 'DOMContentLoaded', function(e){
    //Page loaded, do something
});
//Invoke an event on an element
bean.fire(selectedElement, 'click');
//Remove the event from an element
bean.remove(selectedElement, 'click');

I’ll be trying out a few more of these micro-frameworks for my personal projects in the future as the ability to select only the functionality you need really appeals to me. Are there any other micro-frameworks you’ve used that you’d recommend? Leave me a comment and I’ll check them out.

Update: It just so happens that a handy library website has emerged inspired by the MicroJS website called EveryJS. The website lists all library’s rather than just micro versions. Not all are listed but I’m sure they will be added soon so it’s one to keep your eye on.

JS1k: JavaScript Optimisations

Following up on my post on JS1k I thought I’d put together a small list of optimisations you can use if you’re looking to minify your code before compressing it. When you only have 1024 bytes to play with every byte counts!

Very obvious, store your objects for later use. You may need to use the document / context later so store them in a single byte variable.

1
2
3
4
5
6
7
8
//From:
var canvas = document.getElementById('c')
var context = canvas.getContext('2d')

//To:
d=document
t=d.getElementById('c')
c=t.getContext('2d')

If you are using Math object / functions, don’t repeat ‘Math’ over and over. It may not look much at first but it will pay off and save you loads of bytes

1
2
3
4
5
6
7
8
//From:
var colour = Math.floor(Math.random()*255);

//To:
M=Math
R=M.random
L=M.floor
colour = L(R()*255)

I found myself using 2 Pi and false quite a lot in the arc method, so why not minify them too.

1
2
3
4
5
6
7
//From:
context.arc(posX, posY, radius, 0, Math.PI*2, false);

//To (uses Math example above too):
P=M.PI*2
f=false
context.arc(posX, posY, radius, 0, P, f);

For your ‘draw’ function use an anonymous function within setInterval(). This will save you around 5 bytes.

1
2
3
4
5
6
7
8
9
10
//From:
function d(){
    //Code goes here...
}
setInterval(d,9)

//To:
setInterval(function(){
    //Code goes here...
},9)

When it comes to the canvas API it is necessary to minimise it’s usage at times since the methods can’t be stored like we did with the Math object. For that I used a mixture of arrays and for while loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//From:
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(50, 100, 10, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();

ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(143, 230, 15, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();//Add more if needed...

//To:
A=["red",50,100,10,"blue",143,230,15];
i=2;while(i--){
    D=i*4;
    ctx.fillStyle = A[D];
    ctx.beginPath();
    ctx.arc(A[D+1], A[D+2], A[D+3], 0, P, f);//We stored 2Pi and false in a var above
    //removed closepath() as this is done when fill is called
    ctx.fill();
}

Another quite obvious one, use the ternary operator instead of an if else statement.

1
2
3
4
5
6
7
8
9
10
//From:
if(Math.ceil(Math.random()*2) == 1){
    var result = 1
} else {
    result = -1
}

//To:
Math.ceil(Math.random()*2) == 1 ? result = 1:result = -1
//Remember you can minify the Math functions

An excellent couple of tips from Ben Almans blog post.

1
2
3
4
5
6
7
8
9
10
11
12
13
/*Backwards iterating while loop*/
//From:
for(i=0;i<20;i++){} //19 bytes

//To:
i=20;while(i--){} //17 bytes

/*Use 'this' instead of 'window'*/
//From:
w=window

//To:
w=this

Hopefully you’ve found some of these JavaScript short-cuts useful. Have any more to add to the list? Leave a comment below!

Learning HTML5 Canvas

For a good while now I’ve been wanting to explore generating visualisations using JavaScript, and there really hasn’t been an easier time to do it with web technologies like Canvas and Processing (via processing.js). As with all things in life there’s never enough hours in the day to do everything. I’ve had the excellent book by Daniel Shiffman, ‘Learning Processing‘ which I’m about 4 chapters into; stareing back at me on my desk for 8 months now. It’s all bright and orange and full of cool stuff! But alas no time… until now. Time for me to pull my finger out and learn something new.

In terms of canvas I’ve already gone through quite a few tutorials on the API and how it works, so I’m not quite a complete beginner. If you are just starting out with canvas one set of tutorials I found particularly helpful is located at the Mozilla developer center (MDC). I must admit I’m struggling to find intermediate tutorials; lots of inspirational demonstrations but the code can make your head hurt due to its complexity.

I’ve compiled a list of canvas related demos and sites below, which I’ve been reading. I’m going to concentrate on canvas for the moment then come back to Processing at a later date.

html5 canvas with liquid particles

Liquid Particles demo by Daniel Puhe

Visualisations

  • Liquid Particles: Loving the simplicity and the bright colours. Try leaving the particles to collect into a tight ball then rip it apart!
  • JuicyDrop: If you ever tried Milkdrop for Winamp you will love this port to canvas. There are four examples of the thousands of Milkdrop visualisations available.
  • HTML 5 Audio Experiment: Another particle based visualisation, this time mixed with audio. I don’t think the particles react to the audio (correct me if I’m wrong!) as it seems to be a repeating pattern. But still very cool!
  • 3D landscape on HTML5 Canvas: Superb 3D visualisation by Seb Lee-Delisle. Canvas may only have a 2D context at the moment but with a little JavaScript magic you can create 3D visualisations.
canvas html5 video in 3d space

Blowing up a HTML5 Video in 3D space using canvas by Craftymind

Technical Demos

  • Blowing up HTML5 video: If the addition of plug-in less video wasn’t enough in HTML 5, check out this demo. Blow up a streaming video with a mouse click.
  • Cloth simulation: It may not sound that exciting but the demo is very clever. Pull and push the cloth with your mouse to see how the mesh changes. Maybe one day we will see Maya ported to HTML5 (it could take a while!)
  • Image Evolve: This has to be one of my favourite HTML5 canvas demos so far. Upload an image and watch how the computer generates the same image using overlapping polygons. The image improves over time; leave it a couple of days and a canvas based Mona Lisa can be yours!
  • Raycaster: If you’ve ever played Wolfenstein 3D this demo will look familiar. It may not look too pretty but it’s a great proof of concept.
retro asteroids in HTML5

HTML 5 Asteroids by Doug McInnes

Games

  • HTML 5 Asteroids: If you are into retro arcade games there are plenty to choose from built with HTML5. Here’s the classic ‘Astroids’ for your time wasting pleasure.
  • HTML5 Pacman: Another classic, this time Pacman. A of version of Pacman hit the news recently when Google replaced their logo with a playable version of Pacman and cost 4.2 million hours of productivity. Not bad people!
  • Experimenting With Textures: Much like the Raycaster technical demo above only a little more advanced. The game actually looks to use some of the original Wolfenstein 3D textures. Now where are the German soldiers?
  • Torus: Looking for a 3D version of Tetris? Look no further as Ben Joffe has done exactly that.
Fire by mr doob

One of many experiments by Mr doob, this one is called 'Fire'.

Compilation Sites & Experiments

  • Mr Doob: If you haven’t seen Mr Doobs site you’ve been missing out. Lots of HTML5 and Flash experiments for you to look at. You can learn lots by doing a quick view source!
  • Chrome Experiments: To promote their Chrome browser Google launched Chrome Experiments. The demos available really show off the speed of the V8 JavaScript engine.
  • Hakim.se: If you like particle visualisations you will love the site by Hakim El Hattab. The HTML5 – Keylight demo is superb.
  • Andrew Hoyer: I mentioned this site earlier with the cloth simulation; but Andrews other experiments are also worth looking at. If you like mathematics you will love these demos. On a side note I’m impressed with the site design too!

Wow there’s a lot to look at there, with more and more coming out every day. So little time! If only I didn’t have to sleep…

p01.org: Amazing Experiments using JavaScript

Some websites you come across make you sit back in and say “wow”. Stumbling across p01.org that’s exactly what I said. P01.org is a website showcasing experiments in JavaScript & Canvas by French Web Developer Mathieu Henri, who currently works for Opera. As HTML5 is becoming increasingly popular, more and more of these cool little experiments are popping up; great news for people like myself who are interested in this up and coming technology.

Mathieu’s experiments range over a wide range of areas, from photo manipulation and raytracing to fractal generation and Wolfenstein… amazing stuff! My personal favorites are the 512b JSpongy and 3D Dots Performance Test.

Experiments by p01.org

The 3D dots and 512b JSpongy experiments using Canvas

One thing that isn’t available on the website is an RSS feed for the latest releases, which is a pity as I want to add them to my Google Reader. Luckily with Web Applications like dapper.net it’s easy to create an RSS feed (plus many others) from any website using screen scraping. For anyone else who wants to add p01 to their feed reader, here’s the RSS feed I created.

Currently on page 1 of 212