WebGL - Drawing Points

Hello, aspiring programmers! Today, we're going to embark on an exciting journey into the world of WebGL, specifically focusing on drawing points. As your friendly neighborhood computer teacher, I'll guide you through this adventure step by step. Don't worry if you've never coded before – we'll start from the very basics and work our way up. So, grab your virtual pencils, and let's dive in!

WebGL - Drawing Points

What is WebGL?

Before we start drawing points, let's understand what WebGL is. WebGL (Web Graphics Library) is a powerful JavaScript API that allows us to create 2D and 3D graphics in web browsers. It's like having a magical paintbrush that can draw directly on your web page!

Required Steps

To draw points using WebGL, we need to follow a series of steps. Think of it as a recipe for creating digital art. Here's a table summarizing these steps:

Step Description
1 Get the canvas element
2 Get the WebGL rendering context
3 Define the geometry (vertices)
4 Create a vertex shader
5 Create a fragment shader
6 Create a shader program
7 Load the data into the GPU
8 Set the viewport
9 Clear the canvas
10 Draw the points

Now, let's break down each step and see how they come together to create our masterpiece!

Example – Draw Three Points using WebGL

Let's walk through an example where we'll draw three colorful points on our canvas. I'll explain each part of the code in detail, so you'll understand exactly what's happening.

Step 1: Set up the HTML

First, we need to create an HTML file with a canvas element:

<!DOCTYPE html>
<html>
<head>
    <title>My First WebGL Points</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400">
        Your browser does not support the canvas element.
    </canvas>
    <script src="webgl-points.js"></script>
</body>
</html>

This creates a canvas that will be our drawing board. The JavaScript file we'll create next will do all the magic!

Step 2: Create the JavaScript File

Now, let's create a file named webgl-points.js and start coding our WebGL application:

// Step 1: Get the canvas element
const canvas = document.getElementById('myCanvas');

// Step 2: Get the WebGL rendering context
const gl = canvas.getContext('webgl');

if (!gl) {
    console.error('WebGL not supported');
    throw new Error('WebGL not supported');
}

// Step 3: Define the geometry (vertices)
const vertices = new Float32Array([
    0.0, 0.5,    // Point 1
    -0.5, -0.5,  // Point 2
    0.5, -0.5    // Point 3
]);

// Step 4: Create a vertex shader
const vertexShaderSource = `
    attribute vec2 a_position;
    void main() {
        gl_Position = vec4(a_position, 0.0, 1.0);
        gl_PointSize = 10.0;
    }
`;

const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderSource);
gl.compileShader(vertexShader);

// Step 5: Create a fragment shader
const fragmentShaderSource = `
    precision mediump float;
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
`;

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

// Step 6: Create a shader program
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);

// Step 7: Load the data into the GPU
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

const positionAttributeLocation = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);

// Step 8: Set the viewport
gl.viewport(0, 0, canvas.width, canvas.height);

// Step 9: Clear the canvas
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

// Step 10: Draw the points
gl.drawArrays(gl.POINTS, 0, 3);

Now, let's break down this code and understand what each part does:

Understanding the Code

Steps 1 and 2: Setting up WebGL

const canvas = document.getElementById('myCanvas');
const gl = canvas.getContext('webgl');

Here, we're getting our canvas element and obtaining the WebGL rendering context. This is like getting our paintbrush and palette ready!

Step 3: Defining the Geometry

const vertices = new Float32Array([
    0.0, 0.5,    // Point 1
    -0.5, -0.5,  // Point 2
    0.5, -0.5    // Point 3
]);

We're defining three points in 2D space. The coordinates range from -1 to 1 in both x and y directions. Imagine our canvas divided into four quadrants, with (0,0) at the center.

Steps 4 and 5: Creating Shaders

Shaders are special programs that run on the GPU. We have two types:

  1. Vertex Shader: Determines the position of our points.
  2. Fragment Shader: Determines the color of our points.
const vertexShaderSource = `
    attribute vec2 a_position;
    void main() {
        gl_Position = vec4(a_position, 0.0, 1.0);
        gl_PointSize = 10.0;
    }
`;

const fragmentShaderSource = `
    precision mediump float;
    void main() {
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    }
`;

The vertex shader sets the position and size of our points. The fragment shader sets the color to red (1.0, 0.0, 0.0 in RGB).

Steps 6 and 7: Creating the Program and Loading Data

These steps involve creating a shader program and loading our vertex data into the GPU's memory.

Steps 8 and 9: Setting Up the View

We set the viewport to match our canvas size and clear the canvas to black.

Step 10: Drawing the Points

gl.drawArrays(gl.POINTS, 0, 3);

Finally, we draw our three points!

Conclusion

Congratulations! You've just created your first WebGL application that draws points. This is just the beginning of your journey into the fascinating world of computer graphics. As you continue to explore, you'll be able to create more complex shapes, add animations, and even venture into 3D graphics.

Remember, learning WebGL is like learning to paint – it takes practice and patience. Don't be discouraged if things don't work perfectly the first time. Keep experimenting, and soon you'll be creating digital masterpieces!

In our next lesson, we'll explore how to add different colors to our points and create more complex shapes. Until then, happy coding!

Credits: Image by storyset