Skip to content

Instantly share code, notes, and snippets.

@tchayen
Last active Dec 25, 2018
Embed
What would you like to do?
document.documentElement.style.overflow = 'hidden'
const vertices = new Float32Array([-1.0, -1.0, 1.0, -1.0, 0.0, 1.0])
const vertex = `
attribute vec2 a_position;
void main() {
gl_Position = vec4(a_position, 0, 1);
}`
const fragment = `
precision mediump float;
void main() {
gl_FragColor = vec4(1, 0, 1, 1);
}`
const setUpCanvas = () => {
const canvas = document.createElement('canvas')
canvas.setAttribute('style', `width: 100vw; height: 100vh`)
document.body.appendChild(canvas)
return canvas
}
const createShader = (gl, type, source) => {
const shader = gl.createShader(type)
gl.shaderSource(shader, source)
gl.compileShader(shader)
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (success) return shader
console.error(gl.getShaderInfoLog(shader))
gl.deleteShader(shader)
}
const 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) return program
console.error(gl.getProgramInfoLog(program))
gl.deleteProgram(program)
}
const setup = (gl, program, vertices) => {
gl.clearColor(0, 0, 0, 0)
const positionLocation = gl.getAttribLocation(program, 'a_position')
const positionBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
return {
positionLocation,
positionBuffer,
}
}
const resize = gl => {
const displayWidth = Math.floor(gl.canvas.clientWidth * window.devicePixelRatio)
const displayHeight = Math.floor(gl.canvas.clientHeight * window.devicePixelRatio)
if (gl.canvas.width !== displayWidth || gl.canvas.height !== displayHeight) {
gl.canvas.width = displayWidth
gl.canvas.height = displayHeight
}
}
const draw = (gl, program, positionBuffer, positionLocation) => {
resize(gl)
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.useProgram(program)
gl.enableVertexAttribArray(positionLocation)
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLES, 0, vertices.length / 2)
}
const canvas = setUpCanvas()
const gl = canvas.getContext('webgl')
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertex)
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragment)
const program = createProgram(gl, vertexShader, fragmentShader)
const { positionLocation, positionBuffer } = setup(gl, program, vertices)
const render = () => draw(gl, program, positionBuffer, positionLocation)
render()
window.addEventListener('resize', render)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment