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 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
GISer_Jing5 小时前
Three.js渲染架构:从WebGL到WebGPU的演进
javascript·架构·webgl
贵州数擎科技有限公司2 天前
机械战警 Threejs实现
webgl·three.js
贵州数擎科技有限公司2 天前
霓虹沙尘暴的 Three.js 实现
前端·webgl
GISer_Jing2 天前
深入解析 Three.js:从架构设计到 WebGPU 渲染革命
javascript·信息可视化·webgl
贵州数擎科技有限公司4 天前
曼德勃罗集的 Three.js 实现
webgl·three.js
大松鼠君4 天前
GLSL 动画动作万能规律表
webgl·three.js
小飞侠是个胖子4 天前
底层博弈:在高阶 WebGL 开发中平衡视觉极限与渲染性能
webgl
贵州数擎科技有限公司5 天前
分形金字塔的 Ray Marching 实现
webgl·three.js
:mnong7 天前
PlayCanvas 开源 WebGL/WebGPU 3D 创作平台分析
3d·开源·webgl
Strayer11 天前
在地图上实现管网拓扑批量移动、旋转与缩放(参考图片的实现方式)
gis·webgl·数据可视化