webgl变换矩阵实现图像平移缩放

这种简单的缩放方式和三角形的原始顶点有直接的关系。
原始坐标(X,Y)变换后的坐标为(X * Xs+Tx, Y * Ys+Ty)
若X=0,则在x轴上缩放无效。
若Y=0,则在y轴上缩放无效。
若X=Y=0,则只剩下平移的效果了。


image.png
    var ctx = document.getElementById('canvas').getContext('webgl');

    var vertexShaderSource = "" +
       "attribute vec4 pos;" +
       "uniform mat4 xf;" +
       "void main(){" +
       "gl_Position = xf * pos;" +
       "}";
    var fragementShaderSource = "" +
       "void main(){" +
       "gl_FragColor = vec4(1.0,0.0,0.0,1.0);" +
       "}";

    var program = iniShaders(ctx,vertexShaderSource,fragementShaderSource);
    var data = new Float32Array([
       -0.5,.0,
       0,0.3,
       0.5,0,
    ]);
    var posLocation = ctx.getAttribLocation(program,'pos');
    var xfLocation = ctx.getUniformLocation(program,'xf');
    var buffer = ctx.createBuffer();
    ctx.bindBuffer(ctx.ARRAY_BUFFER,buffer);
    ctx.bufferData(ctx.ARRAY_BUFFER,data,ctx.STATIC_DRAW);
    ctx.vertexAttribPointer(posLocation,2,ctx.FLOAT,false,0,0);
    ctx.enableVertexAttribArray(posLocation);
    var Tx = 0.0;
    var Ty = 0.0;
    var xs = 1.0;
    var ys = 1.0;

    function run() {
        var xf = new Float32Array([
            xs,0.0,0.0,0.0,
            0.0,ys,0.0,0.0,
            0.0,0.0,1.0,0.0,
            Tx,Ty,0.0,1.0,
        ]);

        ctx.uniformMatrix4fv(xfLocation,false,xf);
        ctx.drawArrays(ctx.TRIANGLES,0,3);
    }
    document.addEventListener('keydown',function (ev) {
        console.log(ev); //打印一下看看key的键值
        switch(ev.keyCode){
            case 37:
                Tx -= 0.05;
                break;
            case 38:
                Ty += 0.05;
                break;
            case 39:
                Tx += 0.05;
                break;
            case 40:
                Ty -= 0.05;
                break;
            case 87: //w  Y轴放大
                ys += 0.05;
                break;
            case 83: //s  Y轴缩小
                ys -= 0.05;
                break;
            case 65: //a  X轴缩小
                xs -= 0.05;
                break;
            case 68: //d  X轴放大
                xs += 0.05;
                break;
            case 81: //q  xy轴放大
                xs += 0.05;
                ys += 0.05;
                break;
            case 69: //e  xy轴放大
                xs -= 0.05;
                ys -= 0.05;
                break;
        }
        run();
    });
    run();

你可能感兴趣的:(webgl变换矩阵实现图像平移缩放)