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 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
优雅永不过时·6 天前
原生Three.js 和 Cesium.js 案例 。 智慧城市 数字孪生常用功能列表
前端·javascript·低代码·编辑器·智慧城市·webgl·three.js
travelclover7 天前
在ArcGIS JS API中使用WebGL实现波纹扩散特效
javascript·arcgis·webgl
iloveas201416 天前
three.js+WebGL踩坑经验合集(6.2):负缩放,负定矩阵和行列式的关系(3D版本)
3d·矩阵·webgl
iloveas201417 天前
three.js+WebGL踩坑经验合集(6.1):负缩放,负定矩阵和行列式的关系(2D版本)
线性代数·矩阵·webgl
iloveas201423 天前
three.js+WebGL踩坑经验合集(4.2):为什么不在可视范围内的3D点投影到2D的结果这么不可靠
3d·webgl
iloveas201425 天前
three.js+WebGL踩坑经验合集(2):3D场景被相机裁切后,被裁切的部分依然可以被鼠标碰撞检测得到(射线检测)
webgl
iloveas201425 天前
three.js+WebGL踩坑经验合集(1):THREE.Line无故消失的元凶
webgl
匹马夕阳1 个月前
(十四)WebGL纹理坐标初识
前端框架·图形渲染·webgl
浩哥的技术博客1 个月前
Threejs的学习-入门
前端·前端框架·webgl
xhload3d1 个月前
正泰电工×图扑软件:变电站数字孪生巡检平台
3d·智慧城市·html5·webgl·数字孪生·可视化·变电站·工业互联网·智慧电力·轻量化·电力能源·合作共赢