WebGL Practice Exercises: Essential Techniques for Mastering the Framework

Here’s a simple practice exercise to help you get started with WebGL:

  1. Create an HTML canvas element with an ID of “glCanvas”:
bashCopy code<canvas id="glCanvas"></canvas>
  1. Get a WebGL context from the canvas element:
javascriptCopy codeconst canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
  1. Clear the canvas:
scssCopy codegl.clearColor(0.0, 0.0, 0.0, 1.0); // set the clear color to black
gl.clear(gl.COLOR_BUFFER_BIT); // clear the color buffer
  1. Define the vertices of a triangle and create WebGL buffers for them:
javascriptCopy codeconst positions = [
  0.0, 0.5, 0.0,
  -0.5, -0.5, 0.0,
  0.5, -0.5, 0.0
];

const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
  1. Define the shaders:
csharpCopy codeconst vertexShaderSource = `
  attribute vec3 aPosition;

  void main() {
    gl_Position = vec4(aPosition, 1.0);
  }
`;

const fragmentShaderSource = `
  void main() {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
  }
`;
  1. Compile and link the shaders:
scssCopy codeconst vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);

const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderSource);
gl.compileShader(fragmentShader);

const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
  1. Draw the triangle:
scssCopy codegl.useProgram(program);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const aPosition = gl.getAttribLocation(program, 'aPosition');
gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(aPosition);
gl.drawArrays(gl.TRIANGLES, 0, 3);

This code will draw a simple white triangle on a black background. You can experiment with changing the position of the vertices, the color of the triangle, and the shape of the geometry to create more complex WebGL content.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *