Experiment of the day: Procedural wallpapers

Today was experiments day.
Yesterday I was reading the first chapters of The New Turing Omnibus which is a very good read, both entertaining and instructing. One of the first chapters presented a pretty simple algorithm to generate wallpapers. It strucked me how simple it was. Basically:

1. Input corna, cornb  
2. Input side  
3. for i <-- 1 to 100  
    1. for j <-- 1 to 100
        x <-- corna + i * side / 100
        y <-- cornb + j * side / 100
        c <-- int(x^2 + y^2)
        if c even
            then plot (i, j)

My javascript version (drawing scaled to x4 because big pixels are cool):

function wallpaper () {  
    ctx.clearRect(0, 0, width * 4, height * 4); 
    var cornx = parseInt($("#cornx").val(), 10) || 0;
    var corny = parseInt($('#corny').val(), 10) || 0;
    var side = parseInt($('#side').val(), 10) || 0;
    console.log(cornx, corny, side);
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            var x = cornx + i * side / width;
            var y = corny + j * side / height;
            var c = Math.floor(x * x + y * y);
            if (c % 2 == 0) {
                ctx.fillRect(x * 4, y * 4, 4, 4);
            }
        }
    }
}

And that's it. Extremely simple, but can actually produce very interesting results.

So here is my JS version of it. You can play around with it if you like. Just input random parameters and press enter. You can find interesting values anywhere from 1 to 2309238298...

The diversity of the results produced by this algorithm is quite amazing, and I'm pretty sure someone clever could find a cool use to this.

If you're interested in code, or computing in general, you should totally read this book. It contains plenty of these sort of really cool workshop-things on a wide range of computer science fields. Lots of fun project to do, and cool to read.

Here are some screenshots of the wallpapers:


comments powered by Disqus