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 建立矩阵对象,并传递给着色器的方法参考之前博文,此处不再赘述
相关推荐
IT小白杨2 天前
链上任务与海外社媒多账号:环境隔离工具技术横评
经验分享·webgl·chrome devtools·安全架构·指纹浏览器
AI_AGENT_DEV_AI8 天前
数字孪生项目的开发
webgl
supermapsupport9 天前
SuperMap GIS 基础产品 FAQ 集锦(20260807)
webgl·supermap·idesktopx
supermapsupport9 天前
SuperMap iClient3D for WebGL 如何开启实体对象深度检测
webgl
IT小白杨9 天前
2026Shopee多站点运营的浏览器隔离与移动端云手机方案
经验分享·社交电子·webgl·安全架构·指纹浏览器
echoVic10 天前
同一个 bug,我在 WebGPU 渲染器里犯了两轮:一帧内多次写同一块 buffer
前端·webgl·图形学
用户831348593069813 天前
Vue3+Cesium实现阴天乌云+下雨天气特效
vue.js·webgl·cesium
引山洪0814 天前
Babylon.js 8.x 中文文档整理——Node篇 (上)
前端·webgl
想做后端的前端20 天前
WebGL实现FPS游戏
vue.js·游戏·webgl
ZENERGY-众壹21 天前
延时 5 秒怎么调优:光伏 SCADA 实时画面与 WebGL 拓扑集成的性能复盘
性能优化·webgl·scada·光伏运维·api集成