Webgl gl.viewport change

后端 未结 1 1359
一整个雨季
一整个雨季 2021-02-08 10:45

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.view

1条回答
  •  梦毁少年i
    2021-02-08 11:16

    There is no such thing is gl.viewportWidth or gl.viewportHeight

    If you want to set your perspective matrix you should use canvas.clientWidth and canvas.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 css

    
    
    ...
    
    var width = canvas.clientHeight;
    var height = Math.max(1, canvas.clientHeight);  // prevent divide by 0
    mat4.perspective(45, width / height, 1, 1000, projectionMatrix);
    

    As for the viewport. Use gl.drawingBufferWidth and gl.drawingBufferHeight. That's the correct way to find the size of your drawingBuffer

    gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
    

    Just to be clear there are several things conflated here

    • canvas.width, canvas.height = size you requested the canvas's drawingBuffer to be
    • gl.drawingBufferWidth, gl.drawingBufferHeight = size you actually got. In 99.99% of cases this will be the same as canvas.width, canvas.height.
    • canvas.clientWidth, canvas.clientHeight = size the browser is displaying your canvas.

    To see the difference

    
    

    or

    canvas.width = 10;
    canvas.height = 20;
    canvas.style.width = "30px";
    canvas.style.height = "40px";
    

    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 set canvas.style.width and canvas.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

    • viewport = generally you want this to be the size of your drawingBuffer
    • aspect ratio = generally you want this to be the size your canvas is scaled to

    Given those definitions the width and height used for viewport is often not the same as the width and height used for aspect ratio.

    0 讨论(0)
提交回复
热议问题