Canvas Filters and Particles

experiments

I have to admit, after yesterday’s excitement over discovering Canvas filters, and after digging into them a bit to write the last couple of posts about them, I was somewhat underwhelmed. They didn’t seem as exciting as I initially thought they would be. But had another go with them today, and now I am a believer.

Source

This actually began as an attempt at a physarum simulation (one of the trendy generative algorithms these days). I only got as far as some agents randomly moving around and leaving trails, then did a blur and brightness filter and was blown away at the various effects and the performance. Decided to post it as is and continue working on it.

Pretty sure there was no direct way to achieve affects like this in 2d canvas before filters. Of course you could manually create a blur, but it would be slow. This thing is fast.

This also highlights another benefit to canvas context filters over the same CSS filter applied to the canvas element. Here, the blur is repeatedly applied so it just blurs more and more with each frame. Since the CSS blur is non-destructive, this would be impossible with CSS filters alone.

A little insight to the code. this is the render function:

function render() {
  model.agents.update();
  model.agents.render(context);

  context.filter = `blur(${model.blur}px) brightness(${model.fade}%)`;
  context.drawImage(context.canvas, 0, 0, 400, 400);
  context.filter = "blur()";
}

It updates all the particles and draws them to screen. Then it sets a blur and brightness filter and redraws the canvas back onto itself in order to apply the filter. Finally it removes the filters by setting the filter to an empty blur filter.

Disclaimer

As I said yesterday, filters are an experimental feature and do not yet work in all browsers. In other words, if all you see is a bunch of plain, flat, white lines, you might be using Safari.

Controls: MiniComps

Graphics: BLJS

Support this work

Leave a Reply