Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 792
AlvinfromDiaspar Avatar asked May 30 '14 08:05

AlvinfromDiaspar


People also ask

What aspect ratio is WebGL?

I have a WebGL build which is set up in a standard 16:9 aspect ratio. is there any way to retain that ratio when entering fullscreen mode? For example if someone has a wide 21:9 monitor the build doesn't really feel right even if I set up the UI to adjust correctly.

Does WebGL use canvas?

WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 2D and 3D rendering in an HTML canvas in browsers that support it without the use of plug-ins.


1 Answers

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.

like image 64
Dragan Okanovic Avatar answered Oct 21 '22 18:10

Dragan Okanovic