webgl三角形的缩放
2018-03-30 本文已影响1人
狂暴机甲
在顶点着色器中定义一个uniform变量。用该变量和顶点坐标的x和y想乘实现缩放。
本节的缩放是以坐标原点为基点的,在实际开发中通常以物体的中心为基点进行缩放。
var ctx = document.getElementById('canvas').getContext('webgl');
var vertexShaderSource = "" +
"uniform float pxy;" +
"attribute vec4 aPos;" +
"void main(){" +
"gl_Position.x = aPos.x*pxy;" +
"gl_Position.y = aPos.y*pxy;" +
"gl_Position.z = 1.0;" +
"gl_Position.w = 1.0;" +
"}";
var fragmentShaderSource = "" +
"void main(){" +
"gl_FragColor = vec4(1.0,0.0,0.0,1.0);" +
"}";
var program = iniShaders(ctx,vertexShaderSource,fragmentShaderSource);
var data = new Float32Array([
-0.4,.0,
0.4,.0,
.0,0.4,
]);
var pxy = 1.0;
var pxyLocation = ctx.getUniformLocation(program,'pxy');
ctx.uniform1f(pxyLocation,pxy);
var buffer = ctx.createBuffer();
ctx.bindBuffer(ctx.ARRAY_BUFFER,buffer);
ctx.bufferData(ctx.ARRAY_BUFFER,data,ctx.STATIC_DRAW);
var aposLocation = ctx.getAttribLocation(program,'aPos');
ctx.vertexAttribPointer(aposLocation,2,ctx.FLOAT,false,0,0);
ctx.enableVertexAttribArray(aposLocation)
ctx.drawArrays(ctx.TRIANGLES,0,3);
function fangda() {
pxy = pxy+0.05;
ctx.uniform1f(pxyLocation,pxy);
ctx.drawArrays(ctx.TRIANGLES,0,3);
}
function suoxiao() {
pxy = pxy-0.05;
ctx.uniform1f(pxyLocation,pxy);
ctx.drawArrays(ctx.TRIANGLES,0,3);
}
图片.png