Use COLOURlovers top patterns as random background for you web application

1 minute read

A couple of days ago I stumbled on the COLOURlovers site from the Android Play Store. This site provides a whole lot of beautiful patterns, colors and palettes and has tools to create them. I downloaded an app that randomly changes the background for my tablet, and really like the result. They really have a very beautiful set of patterns to use as a background:

Browse Patterns __ COLOURlovers.png

When browsing their site I noticed they had an API. From this API you can search through all the content on their site, and retrieve links to the patterns:

For instance a GET on http://www.colourlovers.com/api/patterns/top?format=json gives the following result:


...
{
"id":50713,
"title":"pat",
"userName":"florc",
"numViews":40404,
"numVotes":1557,
"numComments":42,
"numHearts":0,
"rank":4,
"dateCreated":"2008-03-03 13:24:06",
"colors":[
"FFFFFF",
"F2EFEB",
"FAF5ED",
"EDE9E4",
"F0ECE9"
],
"description":"",
"url":"http:\/\/www.colourlovers.com\/pattern\/50713\/pat",
"imageUrl":"http:\/\/colourlovers.com.s3.amazonaws.com\/images\/patterns\/50\/50713.png",
"badgeUrl":"http:\/\/www.colourlovers.com\/images\/badges\/n\/50\/50713_pat.png",
"apiUrl":"http:\/\/www.colourlovers.com\/api\/pattern\/50713"
}
...

As a simple experiment I decided to create a web page that uses this API to set a random background based on the top patterns from COLOURlovers. The first problem though was that this API doesn’t support CORS, so I couldn’t directly access the API. Luckily though, this API supports JSONP, so with JSONP I can call this API directly from the web app. Now what do you need to do to get all this working? Not that much, first thing to do, is get the url of a random pattern and set it as the background:

    // We retrieve a set of the 50 top backgrounds
    $.getJSON('http://www.colourlovers.com/api/patterns/top?jsonCallback=?&numResults=50', function(data) {

        // we randomly select one of the elements
        var element = data[Math.floor(Math.random()*50)];

        // we update the body background with the url
        $('body').css({
            "background-image": "url("+ element.imageUrl +")"
        });
    });

This however, doesn’t make the pattern repeat itself. To do this we need to add the following css directives:


        body {
            background-repeat: repeat;
        }

And that’s it, you’ve now got a random repeating background. I created a simple example which you can see here:

Random background from Colourlovers.png

Updated: