JSFiddle - React, Tailwind, and code Playground
HTML
<h1>WebGL Experiment 1 - Draw a triangle</h1>
<canvas id="glCanvas" width="480" height="480">
JavaScript
// Source: https://webglfundamentals.org/webgl/lessons/webgl-fundamentals.html
function createShader(gl, type, source)
{
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (success) {
return shader;
}
console.log(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
}
// Source: https://webglfundamentals.org/webgl/lessons/webgl-fundamentals.html
function createProgram(gl, vertexShader, fragmentShader)
{
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (success) {
return program;
}
console.log(gl.getProgramInfoLog(program));
gl.deleteProgram(program);
}
function resizeCanvasToDisplaySize(canvas, multiplier)
{
multiplier = multiplier || 1;
const width = canvas.clientWidth * multiplier | 0;
const height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
const canvas = document.querySelector("#glCanvas");
const gl = canvas.getContext("webgl");
if( gl == null ){
alert(" [ABORT] Unable to initialized WebGL");
}
// Vertex Shader code => Performs vertex coordinate transforms in the GPU
// Defines the a 3D scene or 2D scene (by ignoring the Z axis).
let code_shader_vertex = `
attribute vec2 position;
void main(){
// Coordinates: X, Y, Z = 0, W = 1 => Ignores the Z axis (2D Scene)
gl_Position = vec4(position, 0, 1.0);
}
`;
// Fragment shader code => Sets color, lights and illumination
let code_shader_fragment = `
void main(){
// Color always green
// Color in (R, G, B, W) => (Red, Green, Blue, W)
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
`;
//...