Creative Coding: Building Re-usable Objects

George Galanakis
HackerNoon.com
Published in
5 min readMar 22, 2017

--

Let’s look at building a simple colourPool object — because making things look nice in Creative Coding has a lot to do with colour. And because we and. And because it’s a great way to see how to build objects, which are really just fancy functions.

Using the Javascript API we can build colours like so:

// using hex values
ctx.fillColor = “#ff0000”;
// using a colour name
ctx.fillColor = “red”;
//using a RGB value
ctx.fillColor = "rgb(255, 0, 0)";
//using a RGBA value
ctx.fillColor = "rgb(255, 0, 0, 1)";
//using a HSL value
ctx.fillColor = "hsl(0, 100, 100)";

But this can often be repetitive, unwieldy and unintuitive, so let’s build a colourPool object, to store an retrieve a colour palette. The concept is directly nicked from Joshua Davis’ Hype Framework. Thanks Josh!

(Shoutout to Joshua for being one of the first people to open source creative coding tutorials, when open source still wasn’t a thing).

So how do we create an object in Javascript? The beauty of Javascript (some would say weakness, but they’re just grumpy coders, we’re artists. Hell Yea!) is it’s just a function. Well is it actually an object. Do we care? We just want to make cool stuff.

So we create a function and we add a return this in order to access the function and it’s inner workings.

// create an object
function colourPool(){
return this;}

To declare our object we just do something like this:

var colours = new ColourPool();

Variables and functions of an object which contain “this”, can be accessed via the dot syntax. Think of “this” as a doorway into the object. So if we wanted a way to add colours, we’d add a function inside the colourPool() object, with a “this” return. The add function takes one parameter which would be the colour we’d want to add, and then we’d push that value ontlo an array to keep note of all our colours:

function colourPool(){ // an empty array where we'll store our colours   
this.pool = [];
// the add function takes in an argument of our colour we want to add to the pool// this.add = function(_colour){} may look funky but
// it's the same as writing: function add(_colour){}
// the this. just now gives us a door to the function
this.add = function(_colour){ // push the new colour onto the pool array
this.pool.push(_colour);
return this;
}
return this;}

(Yea there’s a lot of “this” stuff happening in objects, there are other ways of doing in — in javaScript there are always other ways — like using prototype — but I’ve found these to be even more ugly and verbose and often too hard for people [read: me!] to get their head around.).

So now if we wanted to add colours to our colourPool object we could simply do:

var colours = newColourPool();
colours.add("#cc0000");

And to retrieve our colours we could now simply access the pool array via the dot syntax:

// create a new colourPool and add some colours
var colours = newColourPool();
colours.add("#cc0000");
colours.add("#cccc00");

Returning this from the add function also allows us to chain calls together, like so:

// we can also chain them together
var colours = newColourPool()
.add("#cc0000");
.add("#cccc00");

Pretty neat. But what if we wanted to just get back one random colour, let’s build a function for this:

this.get = function(){ // because arrays start from 0, 
// the last value pool array would be it’s length - 1
// in this case we added two colours,
// so the second colour would be //pool[1]
var colour_pool_length = this.pool.length-1;// get a random value from our pool array
// we use randomInt() to return a whole number
var random_colour = this.pool[randomInt(this.pool.length-1)];return random_colour;}

That’s a bit verbose. So we could squash it all together and simply do:

this.get = function(){    return this.pool[randomInt(this.pool.length-1)];}

And now let’s say we wanted to create a weigted distribution our colours so that the random colour returned is more likely to be say orange than black.

We’d make our add function accept a second condition of weight, and then generate a weighted list.

function colourPool(){  this.pool = [];
this.colour_list = [];
this.weights = [];
this.add = function(_colour, _weight) {
if (_weight == undefined) _weight = 1;
this.pool.push(_colour);
this.weights.push(_weight);
this.colour_list = this.generateWeighedList(this.pool, this.weights);
return this;
}
this.get = function(){
return this.pool[randomInt(this.pool.length-1)];
}
this.generateWeighedList = function(list, weight) {

var weighed_list = [];
// Loop over weights
for (var i = 0; i < weight.length; i++) {
var multiples = weight[i] * 100;
// Loop over the list of items
for (var j = 0; j < multiples; j++) {
weighed_list.push(list[i]);
}
}
return weighed_list; };return this;
}

There’s probably, definitely, a better way to do the weighted list. But for our purposes, unless we adding 100s of colours, it will do fine.

And there we have it. A nifty colourPool function for managing colours. The same principles can be applied to building pretty much any object, which is going to make your creative coding way more fun and productive.

As usual the full code is available on my github, this article is part 12 (be sure to do a pull every now and then, because I’m updating things often): https://github.com/GeorgeGally/creative_coding

See previous editions of Introduction to Creative Coding here: https://hackernoon.com/@radarboy3000

Follow me on Instagram here: https://www.instagram.com/radarboy3000/

Follow me on Twitter here: https://twitter.com/radarboy_japan

And be nice and like my Facebook Page to get tutorial and workshop updates here: https://www.facebook.com/radarboy3000

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

--

--

George Galanakis
HackerNoon.com

Media artist, tinkerer, dreamer. Generative motion, sound and visualizations. Data sculpture and Code Art. https://www.instagram.com/radarboy3000