How to Draw a Rectangle with WebGL


Both WebGL and Canvas are APIs for graphics rendering in web browsers, but they are designed and used differently. If you want to use the WebGL API to achieve the same functions as the Canvas API, you need to master the relevant knowledge of WebGL and apply it in practice.

Here are some examples of WebGL APIs that implement similar functionality to the Canvas API: Canvas API provides simple functions for drawing basic shapes such as rectangles, circles, and lines. WebGL can also achieve similar functions by drawing triangles.

Use Case

Here is a sample code to draw a rectangle using WebGL:

Prepare a canvas container first

<canvas id="myCanvas" width="500" height="500"></canvas>

drawing logic

// Get the WebGL context object
var canvas = document.getElementById('myCanvas');
var gl = canvas.getContext('webgl');

//Vertex coordinates and colors
var vertices = [    -0.5, 0.5, 1.0, 0.0, 0.0,    -0.5, -0.5, 1.0, 0.0, 0.0,    0.5, 0.5, 1.0, 0.0, 0.0,    0.5, -0.5, 1.0, 0.0, 0.0,];

// Create a buffer object
var vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

// Compile vertex and fragment shaders
var vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, `
    attribute vec2 a_position;
    attribute vec3 a_color;
    varying vec3 v_color;
    void main() {
        gl_Position = vec4(a_position, 0.0, 1.0);
        v_color = a_color;

var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, `
    precision mediump float;
    varying vec3 v_color;
    void main() {
        gl_FragColor = vec4(v_color, 1.0);

// Create a shader program
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);

// Enable vertex attributes
var a_position = gl.getAttribLocation(program, 'a_position');
gl.vertexAttribPointer(a_position, 2, gl.FLOAT, false, 20, 0);

var a_color = gl.getAttribLocation(program, 'a_color');
gl.vertexAttribPointer(a_color, 3, gl.FLOAT, false, 20, 8);

// draw rectangle
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);


It should be noted that the WebGL API is more low-level and complex than the Canvas API, requiring developers to have a certain understanding of graphics and linear algebra. At the same time, WebGL can also achieve various 3D and advanced effects more flexibly, such as shadows, reflections, refractions, particle systems, etc., but these require more in-depth understanding and practice.