WebGL Circle
by David Guan
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;
void main() {
float alpha = atan(v_coord.y - 0.5, v_coord.x - 0.5);
float a = sin(alpha * 1.0) / 2.0;
float b = distance(v_coord, vec2(0.5));
gl_FragColor = vec4(v_coord.rg, 1, 1) * (smoothstep(b,b-0.1, a));
}
`;
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 = createProgram(gl, vertexShader, fragmentShader);
const positionAttributeLocation = gl.getAttribLocation(program, 'position');
const colorUniformLocation = gl.getUniformLocation(program, 'color');
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.useProgram(program);
gl.enableVertexAttribArray(positionAttributeLocation);
// gl.vertexAttribPointer(location, size,...