WebGL笔记:矩阵缩放的数学原理和实现

矩阵缩放的数学原理

  • 和平移一样,以同样的原理,也可以理解缩放矩阵
  • 让向量OA基于原点进行缩放
    • x方向上缩放:sx
    • y方向上缩放:sy
    • z方向上缩放:sz
  • 最终得到向量OB

矩阵缩放的应用

  • 比如我要让顶点在x轴向缩放2,y轴向缩放3,轴向缩放4

1 )顶点着色器的核心代码

html 复制代码
<script id="vertexShader" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    // 列主序
    mat4 m4 = mat4(
      2.0, 0.0, 0.0, 0.0,
      0.0, 3.0, 0.0, 0.0,
      0.0, 0.0, 4.0, 0.0,
      0.0, 0.0, 0.0, 1.0
    );
    void main() {
      gl_Position = m4 * a_Position;
    }
</script>

2 )完整代码

html 复制代码
<canvas id="canvas"></canvas>
<script id="vertexShader" type="x-shader/x-vertex">
  attribute vec4 a_Position;
  float sx = 2.0;
  float sy = 3.0;
  float sz = 4.0;
  // 列主序
  mat4 m4 = mat4(
    sx,  0.0, 0.0, 0.0,
    0.0, sy,  0.0, 0.0,
    0.0, 0.0, sz,  0.0,
    0.0, 0.0, 0.0, 1.0
  );
  void main() {
    gl_Position = m4 * a_Position;
  }
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
  void main() {
    gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);
  }
</script>
<script type="module">
  import { initShaders } from './utils.js';

  const canvas = document.getElementById('canvas');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  const gl = canvas.getContext('webgl');

  const vsSource = document.getElementById('vertexShader').innerText;
  const fsSource = document.getElementById('fragmentShader').innerText;
  initShaders(gl, vsSource, fsSource);

  const vertices = new Float32Array([
    0.0, 0.1,
    -0.1, -0.1,
    0.1, -0.1
  ])

  const vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  const a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(a_Position);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
</script>
  • 使用 js 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
l***O5202 天前
免费的WebGL性能优化,纹理压缩与实例化
性能优化·webgl
二川bro2 天前
第38节:WebGL 2.0与Three.js新特性
开发语言·javascript·webgl
qiao若huan喜5 天前
9、webgl 基本概念 + 复合变换 + 平面内容复习
前端·javascript·信息可视化·webgl
qiao若huan喜8 天前
10、webgl 基本概念 + 坐标系统 + 立方体
前端·javascript·信息可视化·webgl
GisCoder8 天前
Cesium教程(9)---编辑Entity图形控制点、拖拽Entity移动、删除Entity
webgl·cesium
qiao若huan喜12 天前
7、webgl 基本概念 + 前置数学知识点(向量 + 矩阵)
线性代数·矩阵·webgl
qiao若huan喜14 天前
6、webgl 基本概念 + 四边形纹理
前端·javascript·信息可视化·webgl
爱看书的小沐15 天前
【小沐杂货铺】基于Three.js绘制三维管道Pipe(WebGL、vue、react)
javascript·vue.js·webgl·three.js·管道·pipe·三维管道
梦凡尘16 天前
webgl 变换矩阵:旋转、平移、缩放
webgl
倚剑仙17 天前
Unity-WebGL开发——用IIS(Internet Information Services)部署webGL工程
unity·游戏引擎·webgl