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 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
该怎么办呢1 天前
cesium核心代码学习-01项目目录及其基本作用
前端·3d·源码·webgl·cesium·webgis
supermapsupport2 天前
SuperMap iClient3D for WebGL 如何实现动态日照阴影效果
webgl
qq_283720052 天前
WebGL基础教程(十四):投影矩阵深度解析——正交 vs 透视,彻底搞懂3D视觉魔法
3d·矩阵·webgl
Jack Yan2 天前
WebGL平台动态修改窗口大小
webgl
小彭努力中2 天前
192.Vue3 + OpenLayers 实战:点击地图 Feature,列表自动滚动定位
vue·webgl·openlayers·geojson·webgis
平行云3 天前
数字孪生信创云渲染系列(一):混合信创与全国产化架构
unity·ue5·3dsmax·webgl·gpu算力·实时云渲染·像素流送
sin°θ_陈3 天前
CVPR 2026的3DGS卷到什么地步?工程语义上探:BrepGaussian如何打通图像到CAD的最后一公里?(Part III 1-3)
python·深度学习·算法·机器学习·3d·webgl
花姐夫Jun3 天前
WebGL学习-czm_getMaterial详解
学习·webgl
花姐夫Jun5 天前
WebGL学习-夹角的归一化
学习·webgl
一拳不是超人6 天前
Three.js一起学-如何通过官方例子高效学习 Three.js?手把手带你“抄”出一个3D动画
前端·webgl·three.js