I have a problem with canvas resizing and gl.viewport
sync.
Let's say that I start with both the canvas 300x300 canvas, and the initialization of gl.viewport
at the same sizes (gl.vieport(0, 0, 300, 300)
).
After that, in browser's console I make my tests:
I'm changing size of my canvas, using jquery, calling something like
$("#scene").width(200).height(200)
After this, i'm calling my resizeWindow function:
function resizeWindow(width, height){ var ww = width === undefined? w.gl.viewportWidth : width; var h = height === undefined? w.gl.viewportHeight : height; h = h <= 0? 1 : h; w.gl.viewport(0, 0, ww, h); mat4.identity(projectionMatrix); mat4.perspective(45, ww / h, 1, 1000.0, projectionMatrix); mat4.identity(modelViewMatrix); }
- function that's synchronizing viewport with required dimensions.
Unfortunatly, my gl.viewport
after this call takes only a part of my canvas.
Could anyone tell me what is going wrong?
There is no such thing is
gl.viewportWidth
orgl.viewportHeight
If you want to set your perspective matrix you should use
canvas.clientWidth
andcanvas.clientHeight
as your inputs to perspective. Those will give you the correct results regardless of what size the browser scales the canvas. As in if you set the canvas auto scale with cssAs for the viewport. Use
gl.drawingBufferWidth
andgl.drawingBufferHeight
. That's the correct way to find the size of your drawingBufferJust to be clear there are several things conflated here
canvas.width
,canvas.height
= size you requested the canvas's drawingBuffer to begl.drawingBufferWidth
,gl.drawingBufferHeight
= size you actually got. In 99.99% of cases this will be the same ascanvas.width
,canvas.height
.canvas.clientWidth
,canvas.clientHeight
= size the browser is displaying your canvas.To see the difference
or
In these cases
canvas.width
will be 10,canvas.height
will be 20,canvas.clientWidth
will be 30,canvas.clientHeight
will be 40. It's common to setcanvas.style.width
andcanvas.style.height
to a percentage so that the browser scales it to fit whatever element it is contained in.On top of that there are the 2 things you brought up
Given those definitions the width and height used for
viewport
is often not the same as the width and height used foraspect ratio
.