2
votes

I try to draw a simple rectangle in webgl ( i use webgl like a 2d api ). The idea is to send attributes ( the points ), and transform them in the vertex shader to fit on the screen. But when i render with the vertex shader : gl_Position = vec4( a_point, 0.0, 1.0 ); i don't see anything. I saw WebGL Fundamentals for 2d webgl and it does not seem to work on my computer. There's rectangles but i think they are not on the good coordinates !

Can you explain me how to draw a rectangle in a special coordinate system :

-width/2 < x < width/2
-height/2 < y < height/2

and then transform them in the vertex shader to have the same position in each browser( chrome, firefox, internet explorer 11. It seems to be very simple but i have not reach my goal. I tried to make a transformation of the vertex in the vertex shader too. Maybe i can use viewport ?

2

2 Answers

7
votes

In WebGL, all coordinates are in the range from -1.00f (f=float) to +1.00f. They automatically represent whatever canvas width and height you got. By default, you don't use absolute pixel numbers in WebGL.

If you set a vertex (point) to be on x=0.00 and y=0.00, it will be in the center of your screen. If one of the coordinates goes below -1 or above +1, it will be outside of your rendered canvas and some pixels from your triangle won't even be passed to fragment shader (fragment = a pixel of your framebuffer).

This way guarantees that all of your objects will have the same relative position and size, no matter how many pixels your canvas will be.

If you want to have an object of a specific pixel size, you can pre-calculate it like this:

var objectWidth = OBJECT_WIDTH_IN_PIXEL / CANVAS_WIDTH; 
var objectHeight = OBJECT_HEIGHT_IN_PIXEL / CANVAS_HEIGHT; 

In some cases, as you might see down below, it's better to know the half width and height in floating point -1.00 to +1.00 universe. To position this object's center into the center of your canvas, you need to setup your vertex data like:

GLfloat vVertices[] = {
    -(objectWidth/2.0),  -(objectHeight/2.0), 0.0,  // Point 1, Triangle 1
    +(objectWidth/2.0),  -(objectHeight/2.0), 0.0,  // Point 2, Triangle 1
    -(objectWidth/2.0),  +(objectHeight/2.0), 0.0,  // Point 3, Triangle 1

    -(objectWidth/2.0),  +(objectHeight/2.0), 0.0,  // Point 4, Triangle 2
    +(objectWidth/2.0),  -(objectHeight/2.0), 0.0,  // Point 5, Triangle 2
    +(objectWidth/2.0),  +(objectHeight/2.0), 0.0   // Point 6, Triangle 2
}

The above vertex data sets up two triangles to create a rectangle in the center of your screen. Many of these things can be found in tutorials like WebGL Fundamentals by Greggman.

1
votes

Please have a look at this post:

http://games.greggman.com/game/webgl-fundamentals/

It shows how to do 2d drawing with WebGL.

I guess you can easily adapt it to suit your need for custom 2d space coordinates.