Experiment: difference with radial gradients in canvas
Another pretty simple idea with a really cool result (above). These are radial gradients drawn on top of each other with a ‘difference’ blend mode.
Way way way back I read a blog post on how to create crumpled paper in Photoshop (I think it was this one). A few years back I used the technique in Filter Forge. This year I was on vacation, in a garden, under a tree, looking out over the sea. And because I’m a coding addict I thought I’d create an interactive version, on my phone. Coding on a phone is slow and feels a bit 1999 in terms of error feedback. But I had all the time in the world.
The idea is simple, but there is a bit more to it than that of course. The gradients attract each other, repel each other, and move around a bit. A nice emergence is that it just keeps on moving without any random motion used.
The coloring is random but always from black to a full color, so the centers are #0FF, #F00, #FFF etc. And because we’re drawing the difference (context.globalCompositeOperation = 'difference';
) we get all the colors in between.
When I started I thought I would draw a lot more particles than the 17 that are in there now, but after tweaking it just looks nicer with 17. So for optimization overkill I used an object chain of prototyped particles (=gradients).
Prototype versus closure
Object prototypes have the advantage that the instance methods are only created once (in memory), as opposed to methods added to object literals. Normally I would code it without prototypes using closures because I don’t like -this-. This would surmount to roughly the same memory wise, but you would have extra scope lookups which are a bit slower.
Object chaining
Another performance design pattern is object chaining. Instead of having an array with instances each instance has a reference to the next one. Nothing fancy, just a tad faster. Although I wonder with these present day engines… but jsperf is still offline.
Anyway, here’s the code. You’ll notice I’ve separated the actual drawing from the math calculations. Time willing, I’m going alter it to a version that uses shaders (here’s a rough).