WebGL笔记:矩阵平移的数学原理和实现

矩阵平移的数学原理

  • 让向量OA位移
    • x方向,tx
    • y方向,ty
    • z方向,tz
  • 最终得到向量OB

矩阵平移的应用

  • 再比如我要让顶点的x移动0.1,y移动0.2,z移动0.3

1 )顶点着色器核心代码

html 复制代码
<script id="vertexShader" type="x-shader/x-vertex">
    attribute vec4 a_Position;
    // 列主序
    mat4 m4 = mat4(
      1.0, 0.0, 0.0, 0.0,
      0.0, 1.0, 0.0, 0.0,
      0.0, 0.0, 1.0, 0.0,
      0.1, 0.2, 0.3, 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 tx = 0.4;
  float ty = 0.3;
  float tz = 0.2;
  // 列主序
  mat4 m4 = mat4(
    1.0, 0.0, 0.0, 0.0,
    0.0, 1.0, 0.0, 0.0,
    0.0, 0.0, 1.0, 0.0,
    tx,  ty,  tz,  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 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
Nicander1 天前
上帝视角看 GPU 学习笔记
webgl·gpu
平行云3 天前
赋能数字孪生:Paraverse平行云实时云渲染平台LarkXR,提供强大的API与SDK用于二次开发和深度集成
3d·unity·ue5·webgl·实时云渲染·云xr
刘皇叔code9 天前
记一次用Three.js展示360°全景图的折腾
webgl·three.js
xhload3d15 天前
场景切换 × 流畅过渡动画实现方案 | 图扑软件
物联网·3d·智慧城市·html5·动画·webgl·数字孪生·可视化·虚拟现实·工业互联网·工控·工业·2d·轻量化·过渡动画
iloveas201419 天前
three.js+WebGL踩坑经验合集(8.3):合理设置camera.near和camera.far缓解实际场景中的z-fighting叠面问题
webgl
失忆爆表症21 天前
基于 MediaPipe + Three.js 的实时姿态可视化前端
前端·webgl
串串狗xk21 天前
使用 webgl 写的新概念笔记应用《赛博城寨》,在三维开放世界里写笔记
javascript·webgl
刘皇叔code24 天前
Three.js后处理UnrealBloomPass的分析
webgl·three.js
掘金安东尼1 个月前
用 WebGL + Solid.js 构建混合材质 Shader
前端·webgl
郝学胜-神的一滴1 个月前
Three.js 材质系统深度解析
javascript·3d·游戏引擎·webgl·材质