Random Polygon Page Backgrounds

My god, it's full of triangles.
Published on Friday, January 30, 2015

You may have noticed that this site uses a randomly generated page background. To see it in action, just hit refresh. It creates a unique series of polygons with gradual horizontal shading in a random muted colors. I figured I would take a couple minutes to explain how it's done.

The magic is from a JavaScript library called Trianglify (GitHub). It can create these sorts of patterns in any size with lots of customizations like polygon size, colors, etc. It then provides the final image as a data URI that can be applied to any CSS element. The GitHub readme actually has an example of setting a background using the library:

var t = new Trianglify();
    var pattern = t.generate(document.body.clientWidth, document.body.clientHeight);
    document.body.setAttribute('style', 'background-image: '+pattern.dataUrl);

The challenge for me was getting the background to look nice. I thought the default random palettes were a little too loud, so I set out to generate my own. I still wanted some randomness though, so I looked for libraries that could generate entire color schemes while allowing some control over things like saturation. I found Please.js (GitHub) which works perfectly. It returns an array of colors to your specifications including how many, what hue or saturation, and other settings.

The final trick was getting the background to blend vertically. Since some of the pages on this site are very long, I didn't want to generate backgrounds that took the entire page height. Therefore the backgrounds needed to be tiled. The solution to this was to tell Trianglify to use a horizontal gradient of random colors, but to use a single color for the vertical gradient. This way, with a muted enough color scheme, the line where the tiling takes place isn't very visible (if you look closely you'll be able to spot it).

My final code looks like this:

var colors = Please.make_color({
        golden: false,
        colors_returned: 3,
        saturation: .4
    });
    var t = new Trianglify({
        x_gradient: colors,
        y_gradient: [""#FFFFFF""]
    });
    var pattern = t.generate(document.body.clientWidth, document.body.clientHeight);
    document.body.setAttribute('style', 'background-image: ' + pattern.dataUrl);