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 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
安大桃子15 小时前
Mapbox GL + Deck.gl 三维实战:Mapbox 加载 Tileset3D 倾斜摄影模型
前端·webgl
爱看书的小沐3 天前
【小沐学Web3D】three.js 加载三维模型(Svelte.js)
javascript·vue.js·webgl·three.js·opengl·web3d·svelte.js
林枫依依3 天前
Unity Webgl在编辑器中报错:Cannot connect to destination host
unity·编辑器·webgl
烛阴3 天前
UV Coordinates & Uniforms -- OpenGL UV坐标和Uniform变量
前端·webgl
陈小峰_iefreer4 天前
stone 3d v3.3.0版本发布,含时间线和连接器等新功能
3d·webgl·metaverse·cadcg
supermapsupport5 天前
SuperMap GIS基础产品FAQ集锦(20250421)
服务器·webgl·supermap·idesktop
zhu_zhu_xia5 天前
JS通过GetCapabilities获取wms服务元数据信息并在SuperMap iClient3D for WebGL进行叠加显示
javascript·3d·webgl
伶俜monster5 天前
光影编程师:Threejs Shader 基础全攻略
前端·webgl·three.js
烛阴5 天前
Swizzling--OpenGL的向量的灵活组合
前端·webgl
前端小崔6 天前
从零开始学习three.js(14):一文详解three.js中的场景Scene
webgl·three.js·数据可视化