WebGL

webgl变换矩阵实现图像移动

2018-04-02  本文已影响3人  狂暴机甲

通过键盘上的上下左右四个按键来控制图像的移动。
使用了 addEvementlistener方法。keydown返回参数在ev变量中。

    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.5,
       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;
    function run() {
        var xf = new Float32Array([
            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,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;
        }
        run();
    });
    run();

运行结果:


图像移动.png
上一篇下一篇

猜你喜欢

热点阅读