Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created July 3, 2021 02:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aleclarson/571e189b7c3b221ab6f8abd416b71da4 to your computer and use it in GitHub Desktop.
Save aleclarson/571e189b7c3b221ab6f8abd416b71da4 to your computer and use it in GitHub Desktop.
// Adapted from: https://digitalbunker.dev/2020/09/13/understanding-gaussian-blurs/
function gaussianBlurMatrix(blurRadius: number) {
if (blurRadius !== Math.round(blurRadius) || blurRadius <= 0) {
throw Error('Blur radius must be a positive integer')
}
const kernel: number[] = []
const kernelWidth = 1 + 2 * blurRadius
const kernelSize = kernelWidth * kernelWidth
const sigma = Math.max(1, blurRadius / 2)
const exponentDenominator = 2 * sigma * sigma
let sum = 0
for (let i = 0; i < kernelSize; i++) {
// Distance from center pixel
const x = (i % kernelWidth) - blurRadius
const y = Math.floor(i / kernelWidth) - blurRadius
const exponentNumerator = -(x * x + y * y)
const kernelValue =
Math.pow(Math.E, exponentNumerator / exponentDenominator) /
(Math.PI * exponentDenominator)
kernel[i] = kernelValue
sum += kernelValue
}
return kernel.reduce(
(matrix, k, i) =>
matrix + k / sum + (i % kernelWidth == kernelWidth - 1 ? '\n' : ' '),
''
)
}
@aleclarson
Copy link
Author

You can use this with feConvolveMatrix

<feConvolveMatrix order={1 + 2 * blurRadius} kernelMatrix={gaussianBlurMatrix(blurRadius)} edgeMode="duplicate" />

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