This sample source code below shows how to implement Gaussian blur filter in OpenGL (WebGL) shading language. The result of this algorithm is a blurry image with relatively good contour lines of objects.
Source Code
The GL shader code below implements a separable Gaussian convolution – once per rows and one per columns.
precision mediump float;
// our texture
uniform sampler2D u_image;
#define KERNEL_SIZE 15
uniform vec2 u_textureSize;
uniform int u_direction;
uniform float u_kernel[KERNEL_SIZE];
void main() {
vec2 textCoord = gl_FragCoord.xy / u_textureSize;
vec2 onePixel = ((u_direction == 0) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)) / u_textureSize;
vec4 meanColor = vec4(0);
int ms = KERNEL_SIZE / 2;
for (int i = 0; i < KERNEL_SIZE; i++)
{
meanColor += texture2D(u_image, textCoord + onePixel*vec2(i - ms))*u_kernel[i];
}
gl_FragColor = meanColor;
}
How it works?
As this is a separable GL implementation of a smooth filter, it will run twice – for horizontal and vertical image blur. This means that the Gaussian kernel for convolution is one dimensional.
The following steps briefly describe how the algorithm works:
- Initially we calculate a Gaussian kernel
- The next step is to load an image inside a Canvas element
- The uniform parameter u_direction selects trace direction – rows or columns
- The u_kernel variable contains the normalized values of the convolution kernel
Bonus Tip
In case you are looking for a pure Java Script solution then you may take a look at our Gaussian blur in plain JS.
Try it Online
You can explore the above algorithm in our free online image processing app.

WEB APPLET
See how it works in the browser!