Search code examples
canvasopengl-eswebgl

How to maintain WebGL Canvas aspect ratio?


I have a Canvas which I'm drawing to via WebGl. My Canvas is sized: 640 width x 480 height.

Im drawing a simple square in the middle. However I was surprised to find that when it is drawn it looks a little stretched horizontally.

What do i need to do to make this square look proper (no stretching)? Note that I have not played with any viewport settings. Im just going thru the early WebGL tutorials.


Solution

  • Left edge of the canvas has x = -1.0, right has x = +1.0, top edge has y = 1.0 and bottom edge has coordinate of y = -1.0.

    In another words, coordinates are normalized across the viewport (xy, z-coord is handled slightly different). Such coordinates are in the clipspace.

    The ratio between the width and the height of the viewport is known as aspect ratio. Aspect ratio is used when constructing the projection matrix.

    When you don't use projection matrix to transform your coordinates into clipspace, you are then directly providing coordinates that will, depending on the size of the viewport, be scaled accordingly.

    Find more details about projecton matrices here and here.

    To solve your problem, simply divide x-coord with aspect ratio.