webgl入门实例-10正交投影基本概念

WebGL 正交投影

正交投影(Orthographic Projection)是WebGL中常用的一种投影方式,它保持物体的平行线在投影后仍然平行,不会产生透视效果(近大远小)。

正交投影基础

正交投影的特点是:

  • 保持物体的实际尺寸不变
  • 平行线在投影后仍保持平行
  • 没有透视缩短效果

在WebGL中实现正交投影

1. 使用矩阵库

通常我们会使用矩阵库(如gl-matrix)来创建正交投影矩阵:

import { mat4 } from 'gl-matrix';

// 创建正交投影矩阵
const projectionMatrix = mat4.create();
mat4.ortho(projectionMatrix, left, right, bottom, top, near, far);

2. 手动创建正交投影矩阵

也可以手动创建正交投影矩阵:

function createOrthographicMatrix(left, right, bottom, top, near, far) {
    const dst = new Float32Array(16);
    
    dst[0] = 2 / (right - left);
    dst[1] = 0;
    dst[2] = 0;
    dst[3] = 0;
    
    dst[4] = 0;
    dst[5] = 2 / (top - bottom);
    dst[6] = 0;
    dst[7] = 0;
    
    dst[8] = 0;
    dst[9] = 0;
    dst[10] = -2 / (far - near);
    dst[11] = 0;
    
    dst[12] = -(right + left) / (right - left);
    dst[13] = -(top + bottom) / (top - bottom);
    dst[14] = -(far + near) / (far - near);
    dst[15] = 1;
    
    return dst;
}

3. 在着色器中使用

顶点着色器中应用正交投影矩阵:

attribute vec4 a_position;
uniform mat4 u_projection;
uniform mat4 u_modelView;

void main() {
    gl_Position = u_projection * u_modelView * a_position;
}

正交投影参数解释

mat4.ortho或手动创建函数接受6个参数:

  • left - 左裁剪面
  • right - 右裁剪面
  • bottom - 下裁剪面
  • top - 上裁剪面
  • near - 近裁剪面
  • far - 远裁剪面

这些参数定义了一个立方体裁剪空间,所有在这个空间内的物体都会被渲染。

示例使用

// 设置正交投影
const projectionMatrix = mat4.create();
// 创建一个从-400到400宽,-300到300高,-1到1深的投影空间
mat4.ortho(projectionMatrix, -400, 400, -300, 300, -1, 1);

// 在渲染循环中
gl.uniformMatrix4fv(uProjectionLocation, false, projectionMatrix);

正交投影 vs 透视投影

特性正交投影透视投影
平行线保持平行会聚于消失点
尺寸保持相同随距离减小
用途CAD、2D游戏、UI3D游戏、真实场景

调整正交投影

可以根据画布大小动态调整正交投影:

function updateProjectionMatrix(gl) {
    const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
    const width = 800;  // 你希望的世界单位宽度
    const height = width / aspect;
    
    mat4.ortho(projectionMatrix, 
               -width/2, width/2, 
               -height/2, height/2, 
               -1, 1);
}

正交投影非常适合2D渲染、UI元素或需要保持物体实际尺寸不变的3D应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值