WebGL透视投影矩阵问题,在两种尺寸上调整画布大小

时间:2017-08-23 14:11:26

标签: javascript canvas webgl

我有一个带透视投影的WebGL查看器,在调整画布高度时工作正常,但在调整画布宽度时没有任何事情发生。

以下是透视投影矩阵代码

function getPerspectiveCamera(fovY, aspect, near,far)
{
  var PerspectiveProjectionMat = mat4.create();
  mat4.identity(PerspectiveProjectionMat);

  var D2R = Math.PI / 180.0;  
  var yScale = 1.0 / Math.tan(D2R * fovY / 2);
  var xScale = yScale / aspect;       
  var nearmfar = near - far;
  var m = [
    xScale, 0, 0, 0,
    0, yScale, 0, 0,
    0, 0, (far + near) / nearmfar, -1,
    0, 0, 2 * far * near / nearmfar, 0
  ];
  for (var i = 0; i < m.length; i++)
     PerspectiveProjectionMat[i] = m[i];

  return PerspectiveProjectionMat;
}

我刚修改了上面的代码,使其在宽高比改变时起作用。 但是当画布宽度小于高度(宽高比小于1)时,模型不适合

修改后的代码是

function getPerspectiveCamera(fovY, aspect, near,far)
{
    var PerspectiveProjectionMat = mat4.create();
    mat4.identity(PerspectiveProjectionMat);        
    var D2R = Math.PI / 180.0;       
    if (aspect > 1) //canvas.width > canvas.height
    {
        var yScale = 1.0 / Math.tan(D2R * fovY / 2);
        var xScale = yScale / aspect;
    }
    else
    {
        var yScale = aspect / Math.tan(D2R * fovY / 2);
        var xScale = yScale / aspect;
        //var fovX = 2 * (Math.atan(Math.tan(utility.degToRad(34 * 0.5)) * aspect) * (180 / Math.PI));
        //var yScale = aspect / Math.tan(D2R * fovY / 2);
        //var xScale = 1.0;// yScale / aspect;           
    }


    var nearmfar = near - far;
    var m = [
        xScale, 0, 0, 0,
        0, yScale, 0, 0,
        0, 0, (far + near) / nearmfar, -1,
        0, 0, 2 * far * near / nearmfar, 0
    ];
    for (var i = 0; i < m.length; i++)
        PerspectiveProjectionMat[i] = m[i];

    return PerspectiveProjectionMat;
}

请向我解释这里有什么问题并给我你的建议来解决它。

添加图片供您参考 Model not fitted properly Model fitted properly

0 个答案:

没有答案