Edge Detection filter
by EMIR MARQUES
HTML
<canvas width="600" height="600"></canvas>
CSS
html,
body {
height: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
Babel + JSX
const gl = document.querySelector('canvas').getContext('webgl');
const canvasWidthHeight = 600;
gl.clearColor(1, 1, 1, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
const vertexShaderSource = `
attribute vec2 position;
varying vec2 v_coord;
void main() {
gl_Position = vec4(position, 0, 1);
v_coord = gl_Position.xy * 0.5 + 0.5;
}
`;
const fragmentShaderSource = `
precision mediump float;
varying vec2 v_coord;
uniform vec2 imageResolution;
uniform sampler2D u_texture;
void main() {
vec2 pos = vec2(v_coord.x, 1.0 - v_coord.y);
vec2 onePixel = vec2(1, 1) / imageResolution;
vec4 color = vec4(0);
mat3 edgeDetectionKernel = mat3(
-1, -1, -1,
-1, 7.3, -1,
-1, -1, -1
);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
vec2 samplePos = pos + vec2(i - 1 , j - 1) * onePixel;
vec4 sampleColor = texture2D(u_texture, samplePos);
sampleColor *= edgeDetectionKernel[i][j];
color += sampleColor;
}
}
color.a = 1.0;
gl_FragColor = color;
}
`;
function createShader(gl, type, shaderSource) {
const shader = gl.createShader(type);
gl.shaderSource(shader, shaderSource);
gl.compileShader(shader);
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success) {
console.warn(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
}
return shader;
}
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
function createProgram(gl, vertexShader, fragmentShader) {
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success) {
console.log(gl.getProgramInfoLog(program));
gl.deleteProgram(program);
}
return program;
}
const program =...