Tuesday, July 30, 2013

JavaScript Art: Session 1 - Contemporary

10 or so years ago when I was big into ActionScript, I bought a book called Flash Math Creativity that really inspired me to make some expressive visuals. By creating and cloning "nodes" and by writing algorithms to alter the position and style of subsequent nodes, we can make some really fun art pieces using simple math.

Since this lesson is browser-based, we'll use JavaScript instead of ActionScript, and for this lesson we'll support Class A browsers. ActionScript and JavaScript are both ECMAScript so feel free to apply logic across both platforms. You can add support for legacy Internet Explorer on your own time, but keep in mind the JScript engine is terribly slow and there is a good chance your masterpiece will crash an old IE8 install.

This is what we will be making today:

Here is the code - we will analyze it below:

The JavaScript:

The CSS:

The Random Colors

First we want to acknowledge how we get random colors. As mentioned, 16777215 == ffffff in hexadecimal, which translate to white. From there, we can generate colors with math using the following:

The DOM Fragment

Secondly, we want to acknowledge that we create a DOM fragment with document.createDocumentFragment and then append all our node divs to it, and only then do we add it to the body. This drastically speeds up our processing. DOM fragments are pretty common in the world of website design and development when using libraries like jQuery, but creating them with vanilla JS isn't seen very often. You can read more about it at MDN.

Make It Your Own

Lastly, during the iteration of all our nodes, we add our randomness and create the art:

Play with those values to greatly change up how your art appears. We used 5,000 nodes for our piece. Have fun!


  1. Great Job! looks great! One suggestion:

    It would make more sense to create the style attributes in the first loop right after you create the element.

    The last step should be appending "frag" to the DOM. Instead of writing the elements to the DOM midway, then getting the elements again, looping through them, and changing it in the browser.

    It's much faster the other way.

    1. Yep I agree it's cleaner too. Good eye :)