WebGl Lesson: How to draw triangle and square

Published on : April 27, 2026

Author:

Category: Uncategorized


Target Output:

Code:

<html>

<head>

<title>Learning WebGL &mdash; lesson 1</title>

<meta http-equiv=”content-type” content=”text/html; charset=ISO-8859-1″>

<script type=”text/javascript” src=”glMatrix-0.9.5.min.js”></script>

<script id=”shader-fs” type=”x-shader/x-fragment”>

precision mediump float;

void main(void) {

gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);

}

</script>

<script id=”shader-vs” type=”x-shader/x-vertex”>

attribute vec3 aVertexPosition;

uniform mat4 uMVMatrix;

uniform mat4 uPMatrix;

void main(void) {

gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);

}

</script>

<script type=”text/javascript”>

var gl;

function initGL(canvas) {

try {

gl = canvas.getContext(“experimental-webgl”);

gl.viewportWidth = canvas.width;

gl.viewportHeight = canvas.height;

} catch (e) {

}

if (!gl) {

alert(“Could not initialise WebGL, sorry :-(“);

}

}

function getShader(gl, id) {

var shaderScript = document.getElementById(id);

if (!shaderScript) {

return null;

}

var str = “”;

var k = shaderScript.firstChild;

while (k) {

if (k.nodeType == 3) {

str += k.textContent;

}

k = k.nextSibling;

}

var shader;

if (shaderScript.type == “x-shader/x-fragment”) {

shader = gl.createShader(gl.FRAGMENT_SHADER);

} else if (shaderScript.type == “x-shader/x-vertex”) {

shader = gl.createShader(gl.VERTEX_SHADER);

} else {

return null;

}

gl.shaderSource(shader, str);

gl.compileShader(shader);

if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {

alert(gl.getShaderInfoLog(shader));

return null;

}

return shader;

}

var shaderProgram;

function initShaders() {

var fragmentShader = getShader(gl, “shader-fs”);

var vertexShader = getShader(gl, “shader-vs”);

shaderProgram = gl.createProgram();

gl.attachShader(shaderProgram, vertexShader);

gl.attachShader(shaderProgram, fragmentShader);

gl.linkProgram(shaderProgram);

if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {

alert(“Could not initialise shaders”);

}

gl.useProgram(shaderProgram);

shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, “aVertexPosition”);

gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, “uPMatrix”);

shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, “uMVMatrix”);

}

var mvMatrix = mat4.create();

var pMatrix = mat4.create();

function setMatrixUniforms() {

gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);

gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);

}

/**

==> Declare two global Variables to hold the buffers. ( triangleVertexPositionBuffer and squareVertexPositionBuffer )

*/

var triangleVertexPositionBuffer;

var squareVertexPositionBuffer;

function initBuffers() {

triangleVertexPositionBuffer = gl.createBuffer(); // We create a buffer for the triangle’s vertex positions.

gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer); // This line tells WebGL that any following operations that act                                                                         on buffers should use the one we specify.

var vertices = [

0.0,  1.0,  0.0,

-1.0, -1.0,  0.0,

1.0, -1.0,  0.0

];

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

triangleVertexPositionBuffer.itemSize = 3;

triangleVertexPositionBuffer.numItems = 3; // vertex positions

squareVertexPositionBuffer = gl.createBuffer();

gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);

vertices = [

1.0,  1.0,  0.0,

-1.0,  1.0,  0.0,

1.0, -1.0,  0.0,

-1.0, -1.0,  0.0

];

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

squareVertexPositionBuffer.itemSize = 3;

squareVertexPositionBuffer.numItems = 4; // vertex positions

}

function drawScene() {

gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); // tell WebGL a little bit about the size of the canvas using the                                                                   viewport function

gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0, pMatrix);

mat4.identity(mvMatrix);

mat4.translate(mvMatrix, [-1.5, 0.0, -7.0]);

gl.bindBuffer(gl.ARRAY_BUFFER, triangleVertexPositionBuffer);

gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, triangleVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

setMatrixUniforms();

gl.drawArrays(gl.TRIANGLES, 0, triangleVertexPositionBuffer.numItems);

mat4.translate(mvMatrix, [3.0, 0.0, 0.0]);

gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);

gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

setMatrixUniforms();

gl.drawArrays(gl.TRIANGLE_STRIP, 0, squareVertexPositionBuffer.numItems);

}

/**

==>     This Function initialize Webgl and Shaders.

*/

function webGLStart() {

var canvas = document.getElementById(“lesson01-canvas”);

initGL(canvas);

initShaders();

initBuffers(); // Initializes some buffers. buffers are things that hold the details of the the triangle and the square that                                    we’re going to be drawing

gl.clearColor(0.0, 0.0, 0.0, 1.0);

gl.enable(gl.DEPTH_TEST);

drawScene();

}

</script>

</head>

<body onload=”webGLStart();”>

<a href=”http://learningwebgl.com/blog/?p=28″>&lt;&lt; Back to Lesson 1</a><br />

<canvas id=”lesson01-canvas” style=”border: none;” width=”500″ height=”500″></canvas>

<br/>

<a href=”http://learningwebgl.com/blog/?p=28″>&lt;&lt; Back to Lesson 1</a><br />

</body>

</html>

Now I am going to describe about the code how it works.

I will start at the bottom of the page

See the following code

<body onload=”webGLStart();”>

<a href=”http://learningwebgl.com/blog/?p=28″>&lt;&lt; Back to Lesson 1</a><br />

<canvas id=”lesson01-canvas” style=”border: none;” width=”500″ height=”500″></canvas>

<br/>

<a href=”http://learningwebgl.com/blog/?p=28″>&lt;&lt; Back to Lesson 1</a><br />

</body>

This is complete body of the page. Everything else in javascript.

Lets scroll up to that function now and take a look at it.

function webGLStart() {
    var canvas = document.getElementById("lesson01-canvas");
    initGL(canvas);
    initShaders();
    initBuffers();

    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.enable(gl.DEPTH_TEST);

    drawScene();
  }

It calls function to initialize webgl and shaders. It initialize some buffers using initBuffers. Buffers are things that hold the details of the triangle and the square. We clear the canvas and we should make it black and that we should do depth testing. These steps are implemented by calls to methods on a gl object. Finally we call the function drawScene. This draws the triangle and the square using the buffers.

We will explain rest of the portion in our next tutorial.


Leave a Reply

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