Skip to content

Instantly share code, notes, and snippets.

@HalfdanJ
Created November 19, 2017 18:53
Show Gist options
  • Save HalfdanJ/97df555e97b71626e1ea276adeaa7bd3 to your computer and use it in GitHub Desktop.
Save HalfdanJ/97df555e97b71626e1ea276adeaa7bd3 to your computer and use it in GitHub Desktop.
export default function LowpassFilter(Fc) {
var Q = 0.707;
var K = Math.tan(Math.PI * Fc);
var norm = 1 / (1 + K / Q + K * K);
this.a0 = K * K * norm;
this.a1 = 2 * this.a0;
this.a2 = this.a0;
this.b1 = 2 * (K * K - 1) * norm;
this.b2 = (1 - K / Q + K * K) * norm;
this.z1 = this.z2 = 0;
this.value = 0;
this.tick = function(value) {
var out = value * this.a0 + this.z1;
this.z1 = value * this.a1 + this.z2 - this.b1 * out;
this.z2 = value * this.a2 - this.b2 * out;
return out;
};
}
@HalfdanJ
Copy link
Author

HalfdanJ commented Oct 24, 2018

// Fc is the frequency that it cuts off. 
// Lower value will smooth more. As you get closer to 1 it wont smooth at all.
// For animation a value between 0.01 and 0.1 isnt uncommon. 

// create a filter (once) that you will re-use
var filter = new LowpassFilter(0.1);

...

// In you loop, call the filter
var filteredValue = filter.tick(unfilteredValue);

@HalfdanJ
Copy link
Author

HalfdanJ commented Oct 24, 2018

This code is ported from ofxBiquadFilter written of openFrameworks and is super useful for animation smoothing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment