town-page/_assets/javascript/shaderCanvas.js

51 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-12-28 03:24:46 +00:00
// STEP 1: Prepare the canvas and get WebGL context
var vertShaderSource = document.getElementById("vertex-shader").text;
var fragShaderSource = document.getElementById("fragment-shader").text;
var canvas = document.getElementById('shader-canvas');
var gl = canvas.getContext('webgl', {
antialias: false,
depth: false
});
// STEP 2: define geometry and store it in buffer objects
var verticies = [-1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0];
var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verticies), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null)
// STEP 3: Create and compile shader programs
// Vert shader:
//var vertCode =
// 'attribute vec2 coordinates;' +
// 'void main(void) {' +
// ' gl_Position = vec4(coordinates, 0.0, 1.0);' +
// '}';
var vertCode = vertShaderSource;
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
// Frag shader:
// var fragCode = 'void main(void) {' +
// 'gl_FragColor = vec4(0.0, 0.3, 0.5, 1.0);' +
// '}';
var fragCode = fragShaderSource;
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
// combine shaders:
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
// STEP 4: Associate the shader program to buffer objects
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coord);
// STEP 5: Draw the object:
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);