愿你出走半生,归来仍是少年
通过顶点着色器实现图形的整体平移。
1.知识点
1.1.齐次坐标
在GLSL 中Vec4进行坐标表达时,作为齐次坐标(x,y,z,w).当w=1时,这个vec4可以表达一个点的三维坐标。在进行平移时,应保证偏移量的W为0。
1.2矢量相加运算
在GLSL中提供了矢量相加运算,在进行平移时可通过矢量相加,进行图形的整体平移。
2.代码
<script setup lang="ts">
import { onMounted, ref } from "vue";
import Gl2Utility from "../../Gl/Gl2Utility";
import VertexBufferUtility from "../../Gl/VertexBufferUtility";
const a_PositionName = "a_Position";
const u_MoveName = "u_Move";
onMounted(() => {
const gl2 = Gl2Utility.GetGl2("canvas");
if (gl2 == null) {
console.error("初始化失败!");
return;
}
//顶点着色器源码
const vertexShaderSource = `
attribute vec4 ${a_PositionName};
uniform vec4 ${u_MoveName};
void main(){
//顶点位置,位于坐标原点
gl_Position =a_Position+${u_MoveName};
}
`;
const fragShaderSource = `
void main(){
//定义片元颜色
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}
`;
const program = Gl2Utility.InitShaders(gl2, vertexShaderSource, fragShaderSource);
if (program == null) {
return;
}
//获取参数位置
const a_PositionLocation = gl2.getAttribLocation(program, a_PositionName);
const u_MoveLocation = gl2.getUniformLocation(program, u_MoveName);
if (a_PositionLocation < 0 || u_MoveLocation == null) {
console.error("获取参数失败!");
return;
}
gl2.uniform4f(u_MoveLocation, 0.5, 0.5, 0., 0.);
const count = VertexBufferUtility.InitFloatXY(gl2, program, a_PositionName, [0.0, 0.5, -0.5, -0.5, 0.5, -0.5]);
//设置清除时的背景色
gl2.clearColor(0., 0., 0., 1.);
//清除
gl2.clear(gl2.COLOR_BUFFER_BIT);
//绘制点
gl2.drawArrays(gl2.TRIANGLES, 0, count);
});
</script>
<template>
<div class="demo_main">
<canvas id="canvas"></canvas>
</div>
</template>
<style scoped>
#canvas {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: blue;
}
.demo_main {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>