愿你出走半生,归来仍是少年!
在点击绘制点的基础上,通过片源着色器给每个点设置颜色。以原点为中心,在一象限的点为红色,三象限为绿色,其他象限为白色。
1.知识点
1.1.Uniform变量
向片源着色器传入的数据变量。
1.2.getUniformLocation
获取Uniform变量的存储地址。
1.3.uniform4f
给指定的Uniform变量写入数据。拥有很多的同族函数。
2.代码
<script setup lang="ts">
import { onMounted, ref } from "vue";
import Gl2Utility from "../../Gl/Gl2Utility";
const a_PositionName = "a_Position";
const u_FragColorName = "u_FragColor";
onMounted(() => {
const gl2 = Gl2Utility.GetGl2("canvas");
if (gl2 == null) {
console.error("初始化失败!");
return;
}
//顶点着色器源码
const vertexShaderSource = `
attribute vec4 ${a_PositionName};
void main(){
//给内置变量gl_PointSize赋值像素大小
gl_PointSize=10.0;
//顶点位置,位于坐标原点
gl_Position =${a_PositionName};
}
`;
const fragShaderSource = `
precision mediump float;
uniform vec4 ${u_FragColorName};
void main(){
//定义片元颜色
gl_FragColor = ${u_FragColorName};
}
`;
const program = Gl2Utility.InitShaders(gl2, vertexShaderSource, fragShaderSource);
if (program == null) {
return;
}
//获取参数位置
const a_PositionLocation = gl2.getAttribLocation(program, a_PositionName);
const u_FragColorLocation = gl2.getUniformLocation(program, u_FragColorName);
if (a_PositionLocation < 0 || u_FragColorLocation == null) {
console.error("获取参数失败!");
return;
}
const canvas = document.getElementById("canvas") as HTMLCanvasElement;
const rect = canvas.getBoundingClientRect();
const pts = new Array();
const colors = new Array();
canvas.onclick = (ev) => {
let x = ev.clientX;
let y = ev.clientY;
x = ((x - rect.left) - rect.width / 2.0) / (rect.width / 2.0);
y = (rect.height / 2.0 - (y - rect.top)) / (rect.height / 2.0);
pts.push([x, y]);
if (x >= 0.0 && y >= 0.0) {//一象限
colors.push([1.0, 0.0, 0.0, 1.0]);
} else if (x < 0.0 && y < 0.0) {//三象限
colors.push([0.0, 1.0, 0.0, 1.0])
} else {//其他
colors.push([1.0, 1.0, 1.0, 1.0]);
}
//设置清除时的背景色
gl2.clearColor(0., 0., 0., 1.);
//清除
gl2.clear(gl2.COLOR_BUFFER_BIT);
for (let i = 0; i < pts.length; i++) {
//参数传入
gl2.vertexAttrib3f(a_PositionLocation, pts[i][0], pts[i][1], 0.);
gl2.uniform4f(u_FragColorLocation, colors[i][0], colors[i][1], colors[i][2], colors[i][3],)
//绘制点
gl2.drawArrays(gl2.POINTS, 0, 1);
}
};
});
</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>