WebGL Shader Example
(() => {
const vert = `
attribute vec3 vec;
void main(void) {
gl_Position = vec4(vec, 1.);
}
`
const frag = `
#ifdef GL_ES
precision highp float;
#endif
uniform float time;
void main(void) {
vec2 uv = gl_FragCoord.xy / vec2(500., 500.);
float w = 1. + cos(uv.y * 60.) * cos(uv.x * 50. + time * 30.);
gl_FragColor = vec4(uv.x, w * .5, w, 1.);
}
`
document.body.style.background = '#000'
const gl = document.body
.appendChild(document.createElement('canvas'))
.getContext('webgl')
Object.assign(gl.canvas.style, {
position: 'absolute',
left: 0,
top: 0
})
with (gl) {
const s = 1;
const verts = [
-s, -s, 0,
s, -s, 0,
-s, s, 0,
s, s, 0,
]
const leng = verts.length / 3
bindBuffer(ARRAY_BUFFER, createBuffer())
bufferData(ARRAY_BUFFER, new Float32Array(verts), STATIC_DRAW)
const vs = createShader(VERTEX_SHADER)
shaderSource(vs, vert)
compileShader(vs)
const fs = createShader(FRAGMENT_SHADER)
const sp = createProgram()
shaderSource(fs, frag)
compileShader(fs)
attachShader(sp, vs)
attachShader(sp, fs)
linkProgram(sp)
useProgram(sp)
const vec = getAttribLocation(sp, 'vec')
vertexAttribPointer(vec, 3, FLOAT, false, 0, 0)
enableVertexAttribArray(vec)
onresize = () => {
const { canvas } = gl
canvas.width = innerWidth
canvas.height = innerHeight
viewport(0, 0, innerWidth, innerHeight)
}
onresize()
disable(DEPTH_TEST)
enable(BLEND)
blendFunc(SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
const startTime = Date.now();
function loop() {
const time = (Date.now() - startTime) / 1000
const uniformTime = gl.getUniformLocation(sp, 'time');
gl.uniform1f(uniformTime, time);
clearColor(0, 0, 0, 1)
clear(COLOR_BUFFER_BIT)
drawArrays(TRIANGLE_STRIP, 0, leng)
requestAnimationFrame(loop)
}
loop()
}
})()
A basic shader setup. This is realistic minus the use of a with
statement…