43 WebGL绘制一个自动旋转的立方体盒子,点击获取点击位置颜色

案例查看地址:点击这里

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
    <style>
        body {
            margin: 0;
        }

        #canvas {
            margin: 0;
            display: block;
        }
    </style>
</head>
<body οnlοad="main()">
<canvas id="canvas" height="800" width="1200"></canvas>
</body>
<script src="webgl/webgl-utils.js"></script>
<script src="webgl/webgl-debug.js"></script>
<script src="webgl/cuon-utils.js"></script>
<script src="webgl/cuon-matrix.js"></script>
<script>
    //设置WebGL全屏显示
    var canvas = document.getElementById("canvas");
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    //顶点着色器
    var vertexShaderSource = "" +
        "attribute vec4 a_Position;\n" +
        "attribute vec4 a_Color;\n" +
        "uniform mat4 u_MvpMatrix;\n" +
        "uniform bool u_Clicked;\n" + //鼠标按下后的标示
        "varying vec4 v_Color;\n" +
        "void main (){\n" +
        "   gl_Position = u_MvpMatrix * a_Position;\n" +
        "   if(u_Clicked){\n" +
        "       v_Color = vec4(1.0,0.0,0.0,1.0);\n" +
        "   }else{\n" +
        "       v_Color = a_Color;\n" +
        "   }\n" +
        "}\n";

    //片元着色器
    var fragmentShaderSource = "" +
        "#ifdef GL_ES\n" +
        "precision mediump float;\n" +
        "#endif\n" +
        "varying vec4 v_Color;\n" +
        "void main(){\n" +
        "   gl_FragColor = v_Color;\n" +
        "}\n";

    function main() {
        //获取WebGL对象
        var gl = getWebGLContext(canvas);

        //初始化着色器
        initShaders(gl, vertexShaderSource, fragmentShaderSource);

        //将数据存入缓冲区
        var n = initVertexBuffers(gl);
        if(n < 0){
            console.log("数据存入缓冲区失败");
            return;
        }

        //设置背景色和开启层级关系
        gl.clearColor(0.0,0.0,0.0,1.0);
        gl.enable(gl.DEPTH_TEST);

        //获取uniform变量的存储位置
        var u_MvpMatrix = gl.getUniformLocation(gl.program,"u_MvpMatrix");
        var u_Clicked = gl.getUniformLocation(gl.program,"u_Clicked");
        if(!u_Clicked || !u_MvpMatrix){
            console.log("无法获取相关的存储位置");
            return;
        }

        //赋值变量
        gl.uniform1i(u_Clicked, 0);

        //设置视点和投影矩阵
        var viewProjectionMatrix = new Matrix4();
        viewProjectionMatrix.setPerspective(30.0, canvas.width/canvas.height, 1.0, 100.0);
        viewProjectionMatrix.lookAt(0.0,0.0,7.0,0.0,0.0,0.0,0.0,1.0,0.0);

        //设置一个自动转圈的变量
        var currentAngle = 0.0;

        canvas.onmousedown = function (e) {
            var picked = false;
            //将u_Clicked变量设置为true,将立方体绘制成纯色
            gl.uniform1i(u_Clicked,1);
            draw(gl,n,currentAngle,viewProjectionMatrix,u_MvpMatrix);
            //通过readPixels来吸取点击位置的颜色
            var pixels = new Uint8Array(4); //存储获取的颜色的变量
            gl.readPixels(e.offsetX, window.innerHeight - e.offsetY,1,1,gl.RGBA,gl.UNSIGNED_BYTE,pixels);

            //判断颜色是否和当前的盒子的颜色一样
            if(pixels[0] == 255){
                picked = true;
            }
            if(picked){
                alert("你点中了盒子");
            }
            console.log(pixels,picked);
            gl.uniform1i(u_Clicked, 0);
            draw(gl,n,currentAngle,viewProjectionMatrix,u_MvpMatrix);
        };

        //定时绘制页面
        var tick = function () {
            currentAngle = animate(currentAngle);
            draw(gl,n,currentAngle,viewProjectionMatrix,u_MvpMatrix);
            requestAnimationFrame(tick);
        };

        tick();
    }

    //修改currentAngle的值
    var last = +new Date();
    var angleStep = 20.0;//每次旋转的速度
    function animate(currentAngle) {
        var now = +new Date();
        var elapsed = now - last;
        last = now;

        //这里是为了保证旋转保证匀速旋转
        var newAngle = currentAngle + (angleStep * elapsed) /1000;
        return newAngle %360;
    }

    //设置顶点数据和将数据存入缓冲区
    function initVertexBuffers(gl) {
        // Create a cube
        //    v6----- v5
        //   /|      /|
        //  v1------v0|
        //  | |     | |
        //  | |v7---|-|v4
        //  |/      |/
        //  v2------v3
        var vertices = new Float32Array([   // Vertex coordinates 顶点的坐标数据
            1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0,    // v0-v1-v2-v3 front
            1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0,    // v0-v3-v4-v5 right
            1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0,    // v0-v5-v6-v1 up
            -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0,    // v1-v6-v7-v2 left
            -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,    // v7-v4-v3-v2 down
            1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0     // v4-v7-v6-v5 back
        ]);

        var colors = new Float32Array([   // Colors 顶点的颜色数据
            0.2, 0.58, 0.82, 0.2, 0.58, 0.82, 0.2, 0.58, 0.82, 0.2, 0.58, 0.82, // v0-v1-v2-v3 front
            0.5, 0.41, 0.69, 0.5, 0.41, 0.69, 0.5, 0.41, 0.69, 0.5, 0.41, 0.69,  // v0-v3-v4-v5 right
            0.0, 0.32, 0.61, 0.0, 0.32, 0.61, 0.0, 0.32, 0.61, 0.0, 0.32, 0.61,  // v0-v5-v6-v1 up
            0.78, 0.69, 0.84, 0.78, 0.69, 0.84, 0.78, 0.69, 0.84, 0.78, 0.69, 0.84, // v1-v6-v7-v2 left
            0.32, 0.18, 0.56, 0.32, 0.18, 0.56, 0.32, 0.18, 0.56, 0.32, 0.18, 0.56, // v7-v4-v3-v2 down
            0.73, 0.82, 0.93, 0.73, 0.82, 0.93, 0.73, 0.82, 0.93, 0.73, 0.82, 0.93 // v4-v7-v6-v5 back
        ]);

        // Indices of the vertices  绘制的索引
        var indices = new Uint8Array([
            0, 1, 2, 0, 2, 3,    // front
            4, 5, 6, 4, 6, 7,    // right
            8, 9, 10, 8, 10, 11,    // up
            12, 13, 14, 12, 14, 15,    // left
            16, 17, 18, 16, 18, 19,    // down
            20, 21, 22, 20, 22, 23     // back
        ]);

        //存入缓冲区
        if (!initArrayBuffer(gl, vertices, gl.FLOAT, 3, "a_Position")) {
            return -1;
        }
        if(!initArrayBuffer(gl, colors, gl.FLOAT, 3, "a_Color")){
            return -1;
        }

        //创建索引缓冲区
        var indexBuffer = gl.createBuffer();
        if(indexBuffer < 0){
            console.log("无法创建缓冲区");
            return -1;
        }

        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,indices,gl.STATIC_DRAW);

        return indices.length;
    }

    function initArrayBuffer(gl, data, type, num, attribute) {
        var buffer = gl.createBuffer();
        if (!buffer) {
            console.log("无法创建缓冲区对象");
            return;
        }
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
        var a_attribute = gl.getAttribLocation(gl.program, attribute);
        if (a_attribute < 0) {
            console.log("无法获取变量的存储位置" + attribute);
            return false;
        }
        gl.vertexAttribPointer(a_attribute, num, type, false, 0, 0);
        gl.enableVertexAttribArray(a_attribute);

        return true;
    }

    //绘制
    var matrix = new Matrix4();
    function draw(gl,n,currentAngle,viewProjectionMatrix,u_MvpMatrix) {
        matrix.set(viewProjectionMatrix);
        matrix.rotate(currentAngle,1.0,0.0,0.0);
        matrix.rotate(currentAngle,0.0,1.0,0.0);
        matrix.rotate(currentAngle,0.0,0.0,1.0);
        gl.uniformMatrix4fv(u_MvpMatrix,false,matrix.elements);

        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);
    }
</script>
</html>

在本案例中,注册了一个点击事件,获取点击位置的颜色的方法gl.readPixels()


指定上面的错误,找到错误了,上图说xy是针对于左上角,经过测试和观看代码发现,其实方法是针对的左下角,左下角,左下角!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值