Somethinghitme

My Code, demos and ideas.

2d Metaballs with canvas!

Thursday, Jun 7, 2012

I read this great article on creating 2d metaballs with XNA. I never really looked into the concept behind them, but after reading that they seemed pretty simple. I decided to try my hand at it using javascript and canvas. The results were pretty awesome (well in my opinion anyway).

Quick attempt at explaining my understanding at metaballs without butchering them

The basic concept is to use a radial gradient, and set an alpha threshold that will be filtered. For example any pixel with an alpha lower than 150 will be set to an alpha of 0. This gives the metaball effect because when the gradients overlap, the areas that are normally hidden now have their alpha values added which brings them above the threshold.

One way to achieve this using canvas and javascript

So basically what I do is create a bunch of points, and set their velocities, positions and sizes.

Next I draw each of these onto a temp canvas

Then finally I read the pixel data, filter the alpha based on a threshold I set, and put the filtered data back onto the main canvas to be displayed.

Check out the demo with added features or the jsfiddle to play around with.