Rendering Primitives

In which you put the utility classes together to render two dots.

Now you are ready to render something besides the background color in your hello-orange application. Open up main.js and add these import lines at the top:

import {VertexAttributes} from './vertex-attributes';
import {ShaderProgram} from './shader-program';
import {VertexArray} from './vertex-array';

Extend the global variables section to declare three references to your VBO, VAO, and shader program:

let canvas;
let attributes;
let shaderProgram;
let vao;

We need these variables to be global because multiple functions will access them. The first function to touch them is initialize, which initializes them as you read earlier:

async function initialize() {
  canvas = document.getElementById('canvas');
  window.gl = canvas.getContext('webgl2');

  const positions = [
    0, 0, 0,
    0.5, 0.5, 0,
  ];

  attributes = new VertexAttributes();
  attributes.addAttribute('position', 2, 3, positions);

  const vertexSource = `
in vec3 position;

void main() {
  gl_PointSize = 10.0;
  gl_Position = vec4(position, 1.0);
}
  `;

  const fragmentSource = `
out vec4 fragmentColor;

void main() {
  fragmentColor = vec4(0.0, 0.0, 1.0, 1.0);
}
  `;

  shaderProgram = new ShaderProgram(vertexSource, fragmentSource);
  vao = new VertexArray(shaderProgram, attributes);

  // Event listeners
  window.addEventListener('resize', onResizeWindow);
  onResizeWindow();
}

Since these definitions are in initialize, the VAO, VBO, and shader program are only defined once. They spend the rest of their life sitting on the GPU.

The render function issues a draw call:

function render() {
  gl.viewport(0, 0, canvas.width, canvas.height);
  gl.clearColor(1, 0.5, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);

  shaderProgram.bind();
  vao.bind();
  vao.drawSequence(gl.POINTS);
  vao.unbind();
  shaderProgram.unbind();
}

When you run your application, do you see two dots? Where are they? What does their location tell you about the bounds of space that WebGL displays?

The dots may be too small to see. On some browsers, you may able to increase their size by adding this line to main in the vertex shader:

gl_PointSize = 10.0;

Try resizing the window. Does the browser re-render your scene?

Try replacing gl.POINTS with gl.LINES. Your vertex shader will be called just twice, but the fragment shader will be called to fill in the pixels between them.