【愚公系列】2023年08月 WEBGL专题-物体的选中


前言

点击事件是用户在计算机屏幕或移动设备上单击(或轻敲)鼠标或触摸屏幕时发生的事件。当用户单击一个可交互元素时,例如按钮、链接或图像,浏览器会触发一个点击事件,通知网页代码用户已单击了该元素。

在Web开发中,开发人员可以通过JavaScript编写代码来响应点击事件,并在用户点击时执行某些操作,例如显示弹出窗口、打开新的页面或更改网页内容。

点击事件不仅适用于Web开发,也适用于桌面应用程序和移动应用程序,例如在Windows操作系统中单击鼠标左键或在iOS或Android设备上轻敲屏幕。

一、物体的选中

1.2D和3D的点击事件

点击事件是用户在计算机屏幕或移动设备上单击(或轻敲)鼠标或触摸屏幕时发生的事件。在二维世界中,点击事件可以应用到网页、游戏、地图等等。在网页中,可以通过JavaScript编写代码来响应用户的点击事件,例如在用户点击一个按钮时触发某个操作或打开一个链接。

在游戏中,点击事件可能用于控制角色移动、交互式元素(例如打开门或宝箱等),或选择物品等。在地图应用中,点击事件可以用于选择特定的地点,放大或缩小地图,或显示详细信息等。

在三维世界中,点击事件通常被用于与3D模型交互,例如选择、移动或旋转3D模型。在WebGL中,点击事件可以应用于用户选中3D模型的操作。开发人员通常使用射线检测技术来检测用户是否单击了3D模型,并在用户单击时触发相应的操作。

2.三维物体选中原理

WEBGL三维物体选中的方法有很多,下面是一些常见的方法:

  1. 基于射线检测:通过从摄像机位置发出一条射线,检测与射线相交的物体,从而判断是否选中了某个物体。

  2. 基于包围盒检测:使用特定的包围盒算法(例如AABB算法),创建一个包围物体的盒子,通过检测鼠标是否在盒子内部来判断是否选中该物体。

  3. 基于网格检测:对于一些有规律的、基于多边形的物体(例如立方体、球体等),可以通过检测是否在其多边形内部来判断是否选中了该物体。

  4. 基于颜色检测:对于每个物体,为其设置一个独特的颜色值,通过检测鼠标点击位置的颜色值,来判断是否选中某个物体。

  5. 基于深度值检测:在渲染时,为每个物体记录其渲染的深度值,通过检测鼠标点击位置的深度值,来判断是否选中某个物体。

需要注意的是,不同的方法适用于不同的场景,选择合适的方法能够提高选中的准确性和效率。同时,在实际应用中,也需要考虑到性能的问题,避免不必要的计算。

下面主要介绍基于颜色检测:选中三维物体的原理就是先将物体在颜色缓冲区的颜色设置为一个特定的值,然后用鼠标点选位置的像素颜色与这个特定值作比较,如果相同则代表选中了物体。

2.1 注册鼠标点击事件

//通过getElementById()方法获取canvas画布
var canvas = document.getElementById('webgl')

//注册鼠标点击事件
canvas.onmousedown = function (ev) {
    
    
  var x = ev.clientX
  var y = ev.clientY
    // 处理鼠标点击事件的逻辑
  }
}
//canvas.addEventListener('click', function(event) {
    
    
//  const x = event.clientX - canvas.offsetLeft;
//  const y = event.clientY - canvas.offsetTop;
//  // 处理鼠标点击事件的逻辑
//});

上述代码中,我们通过 addEventListener 方法为 Canvas 元素注册了 click 事件,并通过 event 参数获取了鼠标点击的坐标。注意,我们需要通过 canvas.offsetLeft 和 canvas.offsetTop 来计算出鼠标点击的相对位置,因为 Canvas 可能在文档中的位置不同。

2.2 顶点着色器作特定值设置处理

const VERTEX_SHADER_SOURCE = `
  uniform bool u_Flag; //是否修改颜色的标识
  varying vec4 v_Color; //声明varying变量v_Color,用来向片元着色器传值顶点颜色信息
  void main() {
    if (u_Flag) {
      v_Color = vec4(R, G, B, R);
    }else {
      //原有处理
    }
  }
`; // 顶点着色器

2.3 告诉顶点着色器修改颜色缓冲区

gl.uniform1i(u_Flag, 1) //告诉顶点着色器把颜色缓冲区修改为特定值
//绘制图形,图形会绘制成特定值指定的颜色
draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)

2.4 读取像素颜色判断是否选中

通过鼠标点选位置获取像素颜色,然后和上一步设置的特定值做比较,如果相等说明选中了物体

var pixels = new Uint8Array(4) //创建Uint8Array类型化数组,接收获取的像素值数据
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels) //读取鼠标点击位置像素颜色

if (获取值 == 特定值) 
{
    
    
  alert('方块被选中! ')
} else {
    
    
  gl.uniform1i(u_Flag, 0) //告诉顶点着色器把颜色缓冲区颜色不变
  draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix) // 重绘方块
}

相关API:gl.readPixels(x, y, width, height, format, type, pixels)

  • 函数功能:从颜色缓冲区中读取由x,y,width,height参数确定的矩形中的所有像素值,并保存在pixels指定的数组中
  • x, y:指定颜色缓冲区中矩形块左上角的坐标
  • width, height:指定矩形的宽度和高度,以像素为单位
  • format:指定像素值的颜色格式,必须为gl.RGBA
  • type:指定像素值的数据格式,必须为gl.UNSIGNED_BYTE
  • pixels:指定用来接收像素数据的Uint8Array类型化数组

2.5 案例源码

1、cuon-matrix.js

// cuon-matrix.js (c) 2012 kanda and matsuda
/** 
 * This is a class treating 4x4 matrix.
 * This class contains the function that is equivalent to OpenGL matrix stack.
 * The matrix after conversion is calculated by multiplying a conversion matrix from the right.
 * The matrix is replaced by the calculated result.
 */

/**
 * Constructor of Matrix4
 * If opt_src is specified, new matrix is initialized by opt_src.
 * Otherwise, new matrix is initialized by identity matrix.
 * @param opt_src source matrix(option)
 */
var Matrix4 = function(opt_src) {
    
    
    var i, s, d;
    if (opt_src && typeof opt_src === 'object' && opt_src.hasOwnProperty('elements')) {
    
    
      s = opt_src.elements;
      d = new Float32Array(16);
      for (i = 0; i < 16; ++i) {
    
    
        d[i] = s[i];
      }
      this.elements = d;
    } else {
    
    
      this.elements = new Float32Array([1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1]);
    }
  };
  
  /**
   * Set the identity matrix.
   * @return this
   */
  Matrix4.prototype.setIdentity = function() {
    
    
    var e = this.elements;
    e[0] = 1;   e[4] = 0;   e[8]  = 0;   e[12] = 0;
    e[1] = 0;   e[5] = 1;   e[9]  = 0;   e[13] = 0;
    e[2] = 0;   e[6] = 0;   e[10] = 1;   e[14] = 0;
    e[3] = 0;   e[7] = 0;   e[11] = 0;   e[15] = 1;
    return this;
  };
  
  /**
   * Copy matrix.
   * @param src source matrix
   * @return this
   */
  Matrix4.prototype.set = function(src) {
    
    
    var i, s, d;
  
    s = src.elements;
    d = this.elements;
  
    if (s === d) {
    
    
      return;
    }
      
    for (i = 0; i < 16; ++i) {
    
    
      d[i] = s[i];
    }
  
    return this;
  };
  
  /**
   * Multiply the matrix from the right.
   * @param other The multiply matrix
   * @return this
   */
  Matrix4.prototype.concat = function(other) {
    
    
    var i, e, a, b, ai0, ai1, ai2, ai3;
    
    // Calculate e = a * b
    e = this.elements;
    a = this.elements;
    b = other.elements;
    
    // If e equals b, copy b to temporary matrix.
    if (e === b) {
    
    
      b = new Float32Array(16);
      for (i = 0; i < 16; ++i) {
    
    
        b[i] = e[i];
      }
    }
    
    for (i = 0; i < 4; i++) {
    
    
      ai0=a[i];  ai1=a[i+4];  ai2=a[i+8];  ai3=a[i+12];
      e[i]    = ai0 * b[0]  + ai1 * b[1]  + ai2 * b[2]  + ai3 * b[3];
      e[i+4]  = ai0 * b[4]  + ai1 * b[5]  + ai2 * b[6]  + ai3 * b[7];
      e[i+8]  = ai0 * b[8]  + ai1 * b[9]  + ai2 * b[10] + ai3 * b[11];
      e[i+12] = ai0 * b[12] + ai1 * b[13] + ai2 * b[14] + ai3 * b[15];
    }
    
    return this;
  };
  Matrix4.prototype.multiply = Matrix4.prototype.concat;
  
  /**
   * Multiply the three-dimensional vector.
   * @param pos  The multiply vector
   * @return The result of multiplication(Float32Array)
   */
  Matrix4.prototype.multiplyVector3 = function(pos) {
    
    
    var e = this.elements;
    var p = pos.elements;
    var v = new Vector3();
    var result = v.elements;
  
    result[0] = p[0] * e[0] + p[1] * e[4] + p[2] * e[ 8] + e[12];
    result[1] = p[0] * e[1] + p[1] * e[5] + p[2] * e[ 9] + e[13];
    result[2] = p[0] * e[2] + p[1] * e[6] + p[2] * e[10] + e[14];
  
    return v;
  };
  
  /**
   * Multiply the four-dimensional vector.
   * @param pos  The multiply vector
   * @return The result of multiplication(Float32Array)
   */
  Matrix4.prototype.multiplyVector4 = function(pos) {
    
    
    var e = this.elements;
    var p = pos.elements;
    var v = new Vector4();
    var result = v.elements;
  
    result[0] = p[0] * e[0] + p[1] * e[4] + p[2] * e[ 8] + p[3] * e[12];
    result[1] = p[0] * e[1] + p[1] * e[5] + p[2] * e[ 9] + p[3] * e[13];
    result[2] = p[0] * e[2] + p[1] * e[6] + p[2] * e[10] + p[3] * e[14];
    result[3] = p[0] * e[3] + p[1] * e[7] + p[2] * e[11] + p[3] * e[15];
  
    return v;
  };
  
  /**
   * Transpose the matrix.
   * @return this
   */
  Matrix4.prototype.transpose = function() {
    
    
    var e, t;
  
    e = this.elements;
  
    t = e[ 1];  e[ 1] = e[ 4];  e[ 4] = t;
    t = e[ 2];  e[ 2] = e[ 8];  e[ 8] = t;
    t = e[ 3];  e[ 3] = e[12];  e[12] = t;
    t = e[ 6];  e[ 6] = e[ 9];  e[ 9] = t;
    t = e[ 7];  e[ 7] = e[13];  e[13] = t;
    t = e[11];  e[11] = e[14];  e[14] = t;
  
    return this;
  };
  
  /**
   * Calculate the inverse matrix of specified matrix, and set to this.
   * @param other The source matrix
   * @return this
   */
  Matrix4.prototype.setInverseOf = function(other) {
    
    
    var i, s, d, inv, det;
  
    s = other.elements;
    d = this.elements;
    inv = new Float32Array(16);
  
    inv[0]  =   s[5]*s[10]*s[15] - s[5] *s[11]*s[14] - s[9] *s[6]*s[15]
              + s[9]*s[7] *s[14] + s[13]*s[6] *s[11] - s[13]*s[7]*s[10];
    inv[4]  = - s[4]*s[10]*s[15] + s[4] *s[11]*s[14] + s[8] *s[6]*s[15]
              - s[8]*s[7] *s[14] - s[12]*s[6] *s[11] + s[12]*s[7]*s[10];
    inv[8]  =   s[4]*s[9] *s[15] - s[4] *s[11]*s[13] - s[8] *s[5]*s[15]
              + s[8]*s[7] *s[13] + s[12]*s[5] *s[11] - s[12]*s[7]*s[9];
    inv[12] = - s[4]*s[9] *s[14] + s[4] *s[10]*s[13] + s[8] *s[5]*s[14]
              - s[8]*s[6] *s[13] - s[12]*s[5] *s[10] + s[12]*s[6]*s[9];
  
    inv[1]  = - s[1]*s[10]*s[15] + s[1] *s[11]*s[14] + s[9] *s[2]*s[15]
              - s[9]*s[3] *s[14] - s[13]*s[2] *s[11] + s[13]*s[3]*s[10];
    inv[5]  =   s[0]*s[10]*s[15] - s[0] *s[11]*s[14] - s[8] *s[2]*s[15]
              + s[8]*s[3] *s[14] + s[12]*s[2] *s[11] - s[12]*s[3]*s[10];
    inv[9]  = - s[0]*s[9] *s[15] + s[0] *s[11]*s[13] + s[8] *s[1]*s[15]
              - s[8]*s[3] *s[13] - s[12]*s[1] *s[11] + s[12]*s[3]*s[9];
    inv[13] =   s[0]*s[9] *s[14] - s[0] *s[10]*s[13] - s[8] *s[1]*s[14]
              + s[8]*s[2] *s[13] + s[12]*s[1] *s[10] - s[12]*s[2]*s[9];
  
    inv[2]  =   s[1]*s[6]*s[15] - s[1] *s[7]*s[14] - s[5] *s[2]*s[15]
              + s[5]*s[3]*s[14] + s[13]*s[2]*s[7]  - s[13]*s[3]*s[6];
    inv[6]  = - s[0]*s[6]*s[15] + s[0] *s[7]*s[14] + s[4] *s[2]*s[15]
              - s[4]*s[3]*s[14] - s[12]*s[2]*s[7]  + s[12]*s[3]*s[6];
    inv[10] =   s[0]*s[5]*s[15] - s[0] *s[7]*s[13] - s[4] *s[1]*s[15]
              + s[4]*s[3]*s[13] + s[12]*s[1]*s[7]  - s[12]*s[3]*s[5];
    inv[14] = - s[0]*s[5]*s[14] + s[0] *s[6]*s[13] + s[4] *s[1]*s[14]
              - s[4]*s[2]*s[13] - s[12]*s[1]*s[6]  + s[12]*s[2]*s[5];
  
    inv[3]  = - s[1]*s[6]*s[11] + s[1]*s[7]*s[10] + s[5]*s[2]*s[11]
              - s[5]*s[3]*s[10] - s[9]*s[2]*s[7]  + s[9]*s[3]*s[6];
    inv[7]  =   s[0]*s[6]*s[11] - s[0]*s[7]*s[10] - s[4]*s[2]*s[11]
              + s[4]*s[3]*s[10] + s[8]*s[2]*s[7]  - s[8]*s[3]*s[6];
    inv[11] = - s[0]*s[5]*s[11] + s[0]*s[7]*s[9]  + s[4]*s[1]*s[11]
              - s[4]*s[3]*s[9]  - s[8]*s[1]*s[7]  + s[8]*s[3]*s[5];
    inv[15] =   s[0]*s[5]*s[10] - s[0]*s[6]*s[9]  - s[4]*s[1]*s[10]
              + s[4]*s[2]*s[9]  + s[8]*s[1]*s[6]  - s[8]*s[2]*s[5];
  
    det = s[0]*inv[0] + s[1]*inv[4] + s[2]*inv[8] + s[3]*inv[12];
    if (det === 0) {
    
    
      return this;
    }
  
    det = 1 / det;
    for (i = 0; i < 16; i++) {
    
    
      d[i] = inv[i] * det;
    }
  
    return this;
  };
  
  /**
   * Calculate the inverse matrix of this, and set to this.
   * @return this
   */
  Matrix4.prototype.invert = function() {
    
    
    return this.setInverseOf(this);
  };
  
  /**
   * Set the orthographic projection matrix.
   * @param left The coordinate of the left of clipping plane.
   * @param right The coordinate of the right of clipping plane.
   * @param bottom The coordinate of the bottom of clipping plane.
   * @param top The coordinate of the top top clipping plane.
   * @param near The distances to the nearer depth clipping plane. This value is minus if the plane is to be behind the viewer.
   * @param far The distances to the farther depth clipping plane. This value is minus if the plane is to be behind the viewer.
   * @return this
   */
  Matrix4.prototype.setOrtho = function(left, right, bottom, top, near, far) {
    
    
    var e, rw, rh, rd;
  
    if (left === right || bottom === top || near === far) {
    
    
      throw 'null frustum';
    }
  
    rw = 1 / (right - left);
    rh = 1 / (top - bottom);
    rd = 1 / (far - near);
  
    e = this.elements;
  
    e[0]  = 2 * rw;
    e[1]  = 0;
    e[2]  = 0;
    e[3]  = 0;
  
    e[4]  = 0;
    e[5]  = 2 * rh;
    e[6]  = 0;
    e[7]  = 0;
  
    e[8]  = 0;
    e[9]  = 0;
    e[10] = -2 * rd;
    e[11] = 0;
  
    e[12] = -(right + left) * rw;
    e[13] = -(top + bottom) * rh;
    e[14] = -(far + near) * rd;
    e[15] = 1;
  
    return this;
  };
  
  /**
   * Multiply the orthographic projection matrix from the right.
   * @param left The coordinate of the left of clipping plane.
   * @param right The coordinate of the right of clipping plane.
   * @param bottom The coordinate of the bottom of clipping plane.
   * @param top The coordinate of the top top clipping plane.
   * @param near The distances to the nearer depth clipping plane. This value is minus if the plane is to be behind the viewer.
   * @param far The distances to the farther depth clipping plane. This value is minus if the plane is to be behind the viewer.
   * @return this
   */
  Matrix4.prototype.ortho = function(left, right, bottom, top, near, far) {
    
    
    return this.concat(new Matrix4().setOrtho(left, right, bottom, top, near, far));
  };
  
  /**
   * Set the perspective projection matrix.
   * @param left The coordinate of the left of clipping plane.
   * @param right The coordinate of the right of clipping plane.
   * @param bottom The coordinate of the bottom of clipping plane.
   * @param top The coordinate of the top top clipping plane.
   * @param near The distances to the nearer depth clipping plane. This value must be plus value.
   * @param far The distances to the farther depth clipping plane. This value must be plus value.
   * @return this
   */
  Matrix4.prototype.setFrustum = function(left, right, bottom, top, near, far) {
    
    
    var e, rw, rh, rd;
  
    if (left === right || top === bottom || near === far) {
    
    
      throw 'null frustum';
    }
    if (near <= 0) {
    
    
      throw 'near <= 0';
    }
    if (far <= 0) {
    
    
      throw 'far <= 0';
    }
  
    rw = 1 / (right - left);
    rh = 1 / (top - bottom);
    rd = 1 / (far - near);
  
    e = this.elements;
  
    e[ 0] = 2 * near * rw;
    e[ 1] = 0;
    e[ 2] = 0;
    e[ 3] = 0;
  
    e[ 4] = 0;
    e[ 5] = 2 * near * rh;
    e[ 6] = 0;
    e[ 7] = 0;
  
    e[ 8] = (right + left) * rw;
    e[ 9] = (top + bottom) * rh;
    e[10] = -(far + near) * rd;
    e[11] = -1;
  
    e[12] = 0;
    e[13] = 0;
    e[14] = -2 * near * far * rd;
    e[15] = 0;
  
    return this;
  };
  
  /**
   * Multiply the perspective projection matrix from the right.
   * @param left The coordinate of the left of clipping plane.
   * @param right The coordinate of the right of clipping plane.
   * @param bottom The coordinate of the bottom of clipping plane.
   * @param top The coordinate of the top top clipping plane.
   * @param near The distances to the nearer depth clipping plane. This value must be plus value.
   * @param far The distances to the farther depth clipping plane. This value must be plus value.
   * @return this
   */
  Matrix4.prototype.frustum = function(left, right, bottom, top, near, far) {
    
    
    return this.concat(new Matrix4().setFrustum(left, right, bottom, top, near, far));
  };
  
  /**
   * Set the perspective projection matrix by fovy and aspect.
   * @param fovy The angle between the upper and lower sides of the frustum.
   * @param aspect The aspect ratio of the frustum. (width/height)
   * @param near The distances to the nearer depth clipping plane. This value must be plus value.
   * @param far The distances to the farther depth clipping plane. This value must be plus value.
   * @return this
   */
  Matrix4.prototype.setPerspective = function(fovy, aspect, near, far) {
    
    
    var e, rd, s, ct;
  
    if (near === far || aspect === 0) {
    
    
      throw 'null frustum';
    }
    if (near <= 0) {
    
    
      throw 'near <= 0';
    }
    if (far <= 0) {
    
    
      throw 'far <= 0';
    }
  
    fovy = Math.PI * fovy / 180 / 2;
    s = Math.sin(fovy);
    if (s === 0) {
    
    
      throw 'null frustum';
    }
  
    rd = 1 / (far - near);
    ct = Math.cos(fovy) / s;
  
    e = this.elements;
  
    e[0]  = ct / aspect;
    e[1]  = 0;
    e[2]  = 0;
    e[3]  = 0;
  
    e[4]  = 0;
    e[5]  = ct;
    e[6]  = 0;
    e[7]  = 0;
  
    e[8]  = 0;
    e[9]  = 0;
    e[10] = -(far + near) * rd;
    e[11] = -1;
  
    e[12] = 0;
    e[13] = 0;
    e[14] = -2 * near * far * rd;
    e[15] = 0;
  
    return this;
  };
  
  /**
   * Multiply the perspective projection matrix from the right.
   * @param fovy The angle between the upper and lower sides of the frustum.
   * @param aspect The aspect ratio of the frustum. (width/height)
   * @param near The distances to the nearer depth clipping plane. This value must be plus value.
   * @param far The distances to the farther depth clipping plane. This value must be plus value.
   * @return this
   */
  Matrix4.prototype.perspective = function(fovy, aspect, near, far) {
    
    
    return this.concat(new Matrix4().setPerspective(fovy, aspect, near, far));
  };
  
  /**
   * Set the matrix for scaling.
   * @param x The scale factor along the X axis
   * @param y The scale factor along the Y axis
   * @param z The scale factor along the Z axis
   * @return this
   */
  Matrix4.prototype.setScale = function(x, y, z) {
    
    
    var e = this.elements;
    e[0] = x;  e[4] = 0;  e[8]  = 0;  e[12] = 0;
    e[1] = 0;  e[5] = y;  e[9]  = 0;  e[13] = 0;
    e[2] = 0;  e[6] = 0;  e[10] = z;  e[14] = 0;
    e[3] = 0;  e[7] = 0;  e[11] = 0;  e[15] = 1;
    return this;
  };
  
  /**
   * Multiply the matrix for scaling from the right.
   * @param x The scale factor along the X axis
   * @param y The scale factor along the Y axis
   * @param z The scale factor along the Z axis
   * @return this
   */
  Matrix4.prototype.scale = function(x, y, z) {
    
    
    var e = this.elements;
    e[0] *= x;  e[4] *= y;  e[8]  *= z;
    e[1] *= x;  e[5] *= y;  e[9]  *= z;
    e[2] *= x;  e[6] *= y;  e[10] *= z;
    e[3] *= x;  e[7] *= y;  e[11] *= z;
    return this;
  };
  
  /**
   * Set the matrix for translation.
   * @param x The X value of a translation.
   * @param y The Y value of a translation.
   * @param z The Z value of a translation.
   * @return this
   */
  Matrix4.prototype.setTranslate = function(x, y, z) {
    
    
    var e = this.elements;
    e[0] = 1;  e[4] = 0;  e[8]  = 0;  e[12] = x;
    e[1] = 0;  e[5] = 1;  e[9]  = 0;  e[13] = y;
    e[2] = 0;  e[6] = 0;  e[10] = 1;  e[14] = z;
    e[3] = 0;  e[7] = 0;  e[11] = 0;  e[15] = 1;
    return this;
  };
  
  /**
   * Multiply the matrix for translation from the right.
   * @param x The X value of a translation.
   * @param y The Y value of a translation.
   * @param z The Z value of a translation.
   * @return this
   */
  Matrix4.prototype.translate = function(x, y, z) {
    
    
    var e = this.elements;
    e[12] += e[0] * x + e[4] * y + e[8]  * z;
    e[13] += e[1] * x + e[5] * y + e[9]  * z;
    e[14] += e[2] * x + e[6] * y + e[10] * z;
    e[15] += e[3] * x + e[7] * y + e[11] * z;
    return this;
  };
  
  /**
   * Set the matrix for rotation.
   * The vector of rotation axis may not be normalized.
   * @param angle The angle of rotation (degrees)
   * @param x The X coordinate of vector of rotation axis.
   * @param y The Y coordinate of vector of rotation axis.
   * @param z The Z coordinate of vector of rotation axis.
   * @return this
   */
  Matrix4.prototype.setRotate = function(angle, x, y, z) {
    
    
    var e, s, c, len, rlen, nc, xy, yz, zx, xs, ys, zs;
  
    angle = Math.PI * angle / 180;
    e = this.elements;
  
    s = Math.sin(angle);
    c = Math.cos(angle);
  
    if (0 !== x && 0 === y && 0 === z) {
    
    
      // Rotation around X axis
      if (x < 0) {
    
    
        s = -s;
      }
      e[0] = 1;  e[4] = 0;  e[ 8] = 0;  e[12] = 0;
      e[1] = 0;  e[5] = c;  e[ 9] =-s;  e[13] = 0;
      e[2] = 0;  e[6] = s;  e[10] = c;  e[14] = 0;
      e[3] = 0;  e[7] = 0;  e[11] = 0;  e[15] = 1;
    } else if (0 === x && 0 !== y && 0 === z) {
    
    
      // Rotation around Y axis
      if (y < 0) {
    
    
        s = -s;
      }
      e[0] = c;  e[4] = 0;  e[ 8] = s;  e[12] = 0;
      e[1] = 0;  e[5] = 1;  e[ 9] = 0;  e[13] = 0;
      e[2] =-s;  e[6] = 0;  e[10] = c;  e[14] = 0;
      e[3] = 0;  e[7] = 0;  e[11] = 0;  e[15] = 1;
    } else if (0 === x && 0 === y && 0 !== z) {
    
    
      // Rotation around Z axis
      if (z < 0) {
    
    
        s = -s;
      }
      e[0] = c;  e[4] =-s;  e[ 8] = 0;  e[12] = 0;
      e[1] = s;  e[5] = c;  e[ 9] = 0;  e[13] = 0;
      e[2] = 0;  e[6] = 0;  e[10] = 1;  e[14] = 0;
      e[3] = 0;  e[7] = 0;  e[11] = 0;  e[15] = 1;
    } else {
    
    
      // Rotation around another axis
      len = Math.sqrt(x*x + y*y + z*z);
      if (len !== 1) {
    
    
        rlen = 1 / len;
        x *= rlen;
        y *= rlen;
        z *= rlen;
      }
      nc = 1 - c;
      xy = x * y;
      yz = y * z;
      zx = z * x;
      xs = x * s;
      ys = y * s;
      zs = z * s;
  
      e[ 0] = x*x*nc +  c;
      e[ 1] = xy *nc + zs;
      e[ 2] = zx *nc - ys;
      e[ 3] = 0;
  
      e[ 4] = xy *nc - zs;
      e[ 5] = y*y*nc +  c;
      e[ 6] = yz *nc + xs;
      e[ 7] = 0;
  
      e[ 8] = zx *nc + ys;
      e[ 9] = yz *nc - xs;
      e[10] = z*z*nc +  c;
      e[11] = 0;
  
      e[12] = 0;
      e[13] = 0;
      e[14] = 0;
      e[15] = 1;
    }
  
    return this;
  };
  
  /**
   * Multiply the matrix for rotation from the right.
   * The vector of rotation axis may not be normalized.
   * @param angle The angle of rotation (degrees)
   * @param x The X coordinate of vector of rotation axis.
   * @param y The Y coordinate of vector of rotation axis.
   * @param z The Z coordinate of vector of rotation axis.
   * @return this
   */
  Matrix4.prototype.rotate = function(angle, x, y, z) {
    
    
    return this.concat(new Matrix4().setRotate(angle, x, y, z));
  };
  
  /**
   * Set the viewing matrix.
   * @param eyeX, eyeY, eyeZ The position of the eye point.
   * @param centerX, centerY, centerZ The position of the reference point.
   * @param upX, upY, upZ The direction of the up vector.
   * @return this
   */
  Matrix4.prototype.setLookAt = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) {
    
    
    var e, fx, fy, fz, rlf, sx, sy, sz, rls, ux, uy, uz;
  
    fx = centerX - eyeX;
    fy = centerY - eyeY;
    fz = centerZ - eyeZ;
  
    // Normalize f.
    rlf = 1 / Math.sqrt(fx*fx + fy*fy + fz*fz);
    fx *= rlf;
    fy *= rlf;
    fz *= rlf;
  
    // Calculate cross product of f and up.
    sx = fy * upZ - fz * upY;
    sy = fz * upX - fx * upZ;
    sz = fx * upY - fy * upX;
  
    // Normalize s.
    rls = 1 / Math.sqrt(sx*sx + sy*sy + sz*sz);
    sx *= rls;
    sy *= rls;
    sz *= rls;
  
    // Calculate cross product of s and f.
    ux = sy * fz - sz * fy;
    uy = sz * fx - sx * fz;
    uz = sx * fy - sy * fx;
  
    // Set to this.
    e = this.elements;
    e[0] = sx;
    e[1] = ux;
    e[2] = -fx;
    e[3] = 0;
  
    e[4] = sy;
    e[5] = uy;
    e[6] = -fy;
    e[7] = 0;
  
    e[8] = sz;
    e[9] = uz;
    e[10] = -fz;
    e[11] = 0;
  
    e[12] = 0;
    e[13] = 0;
    e[14] = 0;
    e[15] = 1;
  
    // Translate.
    return this.translate(-eyeX, -eyeY, -eyeZ);
  };
  
  /**
   * Multiply the viewing matrix from the right.
   * @param eyeX, eyeY, eyeZ The position of the eye point.
   * @param centerX, centerY, centerZ The position of the reference point.
   * @param upX, upY, upZ The direction of the up vector.
   * @return this
   */
  Matrix4.prototype.lookAt = function(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) {
    
    
    return this.concat(new Matrix4().setLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ));
  };
  
  /**
   * Multiply the matrix for project vertex to plane from the right.
   * @param plane The array[A, B, C, D] of the equation of plane "Ax + By + Cz + D = 0".
   * @param light The array which stored coordinates of the light. if light[3]=0, treated as parallel light.
   * @return this
   */
  Matrix4.prototype.dropShadow = function(plane, light) {
    
    
    var mat = new Matrix4();
    var e = mat.elements;
  
    var dot = plane[0] * light[0] + plane[1] * light[1] + plane[2] * light[2] + plane[3] * light[3];
  
    e[ 0] = dot - light[0] * plane[0];
    e[ 1] =     - light[1] * plane[0];
    e[ 2] =     - light[2] * plane[0];
    e[ 3] =     - light[3] * plane[0];
  
    e[ 4] =     - light[0] * plane[1];
    e[ 5] = dot - light[1] * plane[1];
    e[ 6] =     - light[2] * plane[1];
    e[ 7] =     - light[3] * plane[1];
  
    e[ 8] =     - light[0] * plane[2];
    e[ 9] =     - light[1] * plane[2];
    e[10] = dot - light[2] * plane[2];
    e[11] =     - light[3] * plane[2];
  
    e[12] =     - light[0] * plane[3];
    e[13] =     - light[1] * plane[3];
    e[14] =     - light[2] * plane[3];
    e[15] = dot - light[3] * plane[3];
  
    return this.concat(mat);
  }
  
  /**
   * Multiply the matrix for project vertex to plane from the right.(Projected by parallel light.)
   * @param normX, normY, normZ The normal vector of the plane.(Not necessary to be normalized.)
   * @param planeX, planeY, planeZ The coordinate of arbitrary points on a plane.
   * @param lightX, lightY, lightZ The vector of the direction of light.(Not necessary to be normalized.)
   * @return this
   */
  Matrix4.prototype.dropShadowDirectionally = function(normX, normY, normZ, planeX, planeY, planeZ, lightX, lightY, lightZ) {
    
    
    var a = planeX * normX + planeY * normY + planeZ * normZ;
    return this.dropShadow([normX, normY, normZ, -a], [lightX, lightY, lightZ, 0]);
  };
  
  /**
   * Constructor of Vector3
   * If opt_src is specified, new vector is initialized by opt_src.
   * @param opt_src source vector(option)
   */
  var Vector3 = function(opt_src) {
    
    
    var v = new Float32Array(3);
    if (opt_src && typeof opt_src === 'object') {
    
    
      v[0] = opt_src[0]; v[1] = opt_src[1]; v[2] = opt_src[2];
    } 
    this.elements = v;
  }
  
  /**
    * Normalize.
    * @return this
    */
  Vector3.prototype.normalize = function() {
    
    
    var v = this.elements;
    var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c*c+d*d+e*e);
    if(g){
    
    
      if(g == 1)
          return this;
     } else {
    
    
       v[0] = 0; v[1] = 0; v[2] = 0;
       return this;
     }
     g = 1/g;
     v[0] = c*g; v[1] = d*g; v[2] = e*g;
     return this;
  };
  
  /**
   * Constructor of Vector4
   * If opt_src is specified, new vector is initialized by opt_src.
   * @param opt_src source vector(option)
   */
  var Vector4 = function(opt_src) {
    
    
    var v = new Float32Array(4);
    if (opt_src && typeof opt_src === 'object') {
    
    
      v[0] = opt_src[0]; v[1] = opt_src[1]; v[2] = opt_src[2]; v[3] = opt_src[3];
    } 
    this.elements = v;
  }

2、鼠标点击选中立方体

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title></title>
</head>

<body>
  <!--通过canvas标签创建一个800px*800px大小的画布-->
  <canvas id="webgl" width="800" height="800"></canvas>
  <script type="text/javascript" src="./lib/cuon-matrix.js"></script>
  <script>
    //顶点着色器
    var VSHADER_SOURCE = '' +
      'attribute vec4 a_Position;\n' + //声明attribute变量a_Position,用来存放顶点位置信息
      'attribute vec4 a_Color;\n' + //声明attribute变量a_Color,用来存放顶点颜色信息
      'uniform mat4 u_MvpMatrix;\n' + //声明uniform变量u_MvpMatrix,用来存放模型视图投影组合矩阵
      'uniform bool u_Clicked;\n' + //声明uniform变量u_Clicked,用来存放鼠标是否选中方块
      'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来向片元着色器传值顶点颜色信息

      'void main(){\n' +
      '  gl_Position = u_MvpMatrix * a_Position;\n' + //将模型视图投影组合矩阵与顶点坐标相乘赋值给顶点着色器内置变量gl_Position
      '  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 FSHADER_SOURCE = '' +
      '#ifdef GL_ES\n' +
      ' precision mediump float;\n' + // 设置精度
      '#endif\n' +
      'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
      'void main(){\n' +
      '  gl_FragColor = v_Color;\n' + //将顶点着色器传送的片元颜色赋值给内置变量gl_FragColor
      '}\n'

    //初始化着色器函数
    function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
      
      
      //创建顶点着色器对象
      var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
      //创建片元着色器对象
      var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)

      if (!vertexShader || !fragmentShader) {
      
      
        return null
      }

      //创建程序对象program
      var program = gl.createProgram()
      if (!gl.createProgram()) {
      
      
        return null
      }
      //分配顶点着色器和片元着色器到program
      gl.attachShader(program, vertexShader)
      gl.attachShader(program, fragmentShader)
      //链接program
      gl.linkProgram(program)

      //检查程序对象是否连接成功
      var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
      if (!linked) {
      
      
        var error = gl.getProgramInfoLog(program)
        console.log('程序对象连接失败: ' + error)
        gl.deleteProgram(program)
        gl.deleteShader(fragmentShader)
        gl.deleteShader(vertexShader)
        return null
      }
      //使用program
      gl.useProgram(program)
      gl.program = program
      //返回程序program对象
      return program
    }

    function loadShader(gl, type, source) {
      
      
      // 创建顶点着色器对象
      var shader = gl.createShader(type)
      if (shader == null) {
      
      
        console.log('创建着色器失败')
        return null
      }

      // 引入着色器源代码
      gl.shaderSource(shader, source)

      // 编译着色器
      gl.compileShader(shader)

      // 检查顶是否编译成功
      var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
      if (!compiled) {
      
      
        var error = gl.getShaderInfoLog(shader)
        console.log('编译着色器失败: ' + error)
        gl.deleteShader(shader)
        return null
      }

      return shader
    }

    function init() {
      
      
      //通过getElementById()方法获取canvas画布
      var canvas = document.getElementById('webgl')
      //通过方法getContext()获取WebGL上下文
      var gl = canvas.getContext('webgl')
      //初始化着色器
      if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
      
      
        console.log('初始化着色器失败')
        return
      }

      // 设置canvas的背景色
      gl.clearColor(0.0, 0.0, 0.0, 1.0)

      //初始化顶点坐标和顶点颜色
      var n = initVertexBuffers(gl)

      setMatrixAndDraw(gl, n, canvas)

    }

    //设置矩阵并绘图
    function setMatrixAndDraw(gl, n, canvas) {
      
      

      //开启隐藏面消除
      gl.enable(gl.DEPTH_TEST)

      //清空颜色和深度缓冲区
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

      //获取顶点着色器uniform变量u_MvpMatrix、u_Clicked的存储地址
      var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix')
      var u_Clicked = gl.getUniformLocation(gl.program, 'u_Clicked')
      if (!u_MvpMatrix || !u_Clicked) {
      
      
        console.log('获取uniform变量u_MvpMatrix或u_Clicked的存储地址失败')
        return
      }

      //创建视图投影矩阵
      var viewProjMatrix = new Matrix4()
      viewProjMatrix.setPerspective(30.0, canvas.width / canvas.height, 1.0, 100.0)
      viewProjMatrix.lookAt(0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)

      gl.uniform1i(u_Clicked, 0) //给顶点着色器uniform变量u_Clicked传值

      var currentAngle = 0.0 // 当前旋转的角度
      //注册鼠标点击事件
      canvas.onmousedown = function (ev) {
      
      
        var x = ev.clientX
        var y = ev.clientY
        var rect = ev.target.getBoundingClientRect()
        if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
      
      
          //获取点击位置在canvas坐标系中的值
          var x_in_canvas = x - rect.left
          var y_in_canvas = rect.bottom - y
          checkCubeIsSelected(gl, n, x_in_canvas, y_in_canvas, currentAngle, u_Clicked, viewProjMatrix, u_MvpMatrix)
        }
      }

      var tick = function () {
      
       //动画循环
        currentAngle = getCurrentAngle(currentAngle)
        draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)
        requestAnimationFrame(tick, canvas)
      }
      tick()
    }

    //初始化顶点坐标和顶点颜色
    function initVertexBuffers(gl) {
      
      

      var v0 = [1.0, 1.0, 1.0]
      var v1 = [-1.0, 1.0, 1.0]
      var v2 = [-1.0, -1.0, 1.0]
      var v3 = [1.0, -1.0, 1.0]
      var v4 = [1.0, -1.0, -1.0]
      var v5 = [1.0, 1.0, -1.0]
      var v6 = [-1.0, 1.0, -1.0]
      var v7 = [-1.0, -1.0, -1.0]

      //顶点
      var vertices = new Float32Array([
        ...v0, ...v1, ...v2, ...v3, // 前
        ...v0, ...v3, ...v4, ...v5, // 右
        ...v0, ...v5, ...v6, ...v1, // 上
        ...v1, ...v6, ...v7, ...v2, // 左
        ...v7, ...v4, ...v3, ...v2, // 下
        ...v4, ...v7, ...v6, ...v5 // 后
      ])

      var fontColor = [0.2, 0.58, 0.82]
      var backColor = [0.73, 0.82, 0.93]
      var leftColor = [0.78, 0.69, 0.84]
      var rightColor = [0.5, 0.41, 0.69]
      var topColor = [0.0, 0.32, 0.61]
      var downColor = [0.32, 0.18, 0.56]
      // 顶点的颜色
      var colors = new Float32Array([
        ...fontColor, ...fontColor, ...fontColor, ...fontColor, // v0-v1-v2-v3 前
        ...rightColor, ...rightColor, ...rightColor, ...rightColor, // v0-v3-v4-v5 右
        ...topColor, ...topColor, ...topColor, ...topColor, // v0-v5-v6-v1 上
        ...leftColor, ...leftColor, ...leftColor, ...leftColor, // v1-v6-v7-v2 左
        ...downColor, ...downColor, ...downColor, ...downColor, // v7-v4-v3-v2 下
        ...backColor, ...backColor, ...backColor, ...backColor, // v4-v7-v6-v5 后
      ])

      // 绘制的索引
      var indices = new Uint8Array([
        0, 1, 2, 0, 2, 3, // 前
        4, 5, 6, 4, 6, 7, // 右
        8, 9, 10, 8, 10, 11, // 上
        12, 13, 14, 12, 14, 15, // 左
        16, 17, 18, 16, 18, 19, // 下
        20, 21, 22, 20, 22, 23 // 后
      ])

      if (!initArrayBuffer(gl, vertices, 3, gl.FLOAT, 'a_Position')) {
      
      
        return -1
      }

      if (!initArrayBuffer(gl, colors, 3, gl.FLOAT, 'a_Color')) {
      
      
        return -1
      }

      //创建缓冲区对象
      var indexBuffer = gl.createBuffer()

      //将顶点索引写入缓冲区对象
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW)

      return indices.length

    }

    //检查点击是否在方块上
    function checkCubeIsSelected(gl, n, x, y, currentAngle, u_Clicked, viewProjMatrix, u_MvpMatrix) {
      
      
      gl.uniform1i(u_Clicked, 1) //给顶点着色器uniform变量u_Clicked传值1
      //绘制图形,顶点着色器中根据u_Clicked值将方块绘制为红色,即RGBA值的R分量为255
      draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)

      var pixels = new Uint8Array(4) //创建Uint8Array类型化数组,接收获取的像素值数据
      gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels) //读取鼠标点击位置像素颜色

      if (pixels[0] == 255) // pixels[0]即RGBA值的R分量的值等于255说明选中方块
      {
      
      
        alert('方块被选中! ')
      } else {
      
      
        gl.uniform1i(u_Clicked, 0) //未选中给顶点着色器uniform变量u_Clicked传值0
        draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix) // 重绘方块
      }

    }

    var g_MvpMatrix = new Matrix4() //模型视图投影矩阵 
    function draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix) {
      
      
      //计算模型视图投影矩阵 
      g_MvpMatrix.set(viewProjMatrix)
      g_MvpMatrix.rotate(currentAngle, 1.0, 0.0, 0.0)
      g_MvpMatrix.rotate(currentAngle, 0.0, 1.0, 0.0)
      g_MvpMatrix.rotate(currentAngle, 0.0, 0.0, 1.0)

      //模型视图投影矩阵的计算结果传给uniform变量u_MvpMatrix
      gl.uniformMatrix4fv(u_MvpMatrix, false, g_MvpMatrix.elements)

      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
      gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0) //绘图
    }

    var g_LastTime = Date.now() // 上次绘制的时间
    var ANGLE_SET = 30.0 // 旋转速度(度/秒)
    function getCurrentAngle(angle) {
      
      
      var now = Date.now()
      var elapsed = now - g_LastTime //上次调用与当前时间差
      g_LastTime = now
      var newAngle = angle + (ANGLE_SET * elapsed) / 1000.0
      return newAngle %= 360
    }

    function initArrayBuffer(gl, data, num, type, attribute) {
      
      
      //创建缓冲区对象
      var buffer = gl.createBuffer()
      //将顶点坐标和顶点颜色信息写入缓冲区对象
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
      gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW)

      //获取顶点着色器attribute变量存储地址, 分配缓存并开启
      var a_Attribute = gl.getAttribLocation(gl.program, attribute)
      gl.vertexAttribPointer(a_Attribute, num, type, false, 0, 0)
      gl.enableVertexAttribArray(a_Attribute)

      return true
    }

    init()
  </script>
</body>

</html>

在这里插入图片描述
3、鼠标点击选中立方体一个表面

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title></title>
</head>

<body>
  <!--通过canvas标签创建一个800px*800px大小的画布-->
  <canvas id="webgl" width="800" height="800"></canvas>
  <script type="text/javascript" src="../lib/cuon-matrix.js"></script>
  <script>
    //顶点着色器
    var VSHADER_SOURCE = '' +
      'attribute vec4 a_Position;\n' + //声明attribute变量a_Position,用来存放顶点位置信息
      'attribute vec4 a_Color;\n' + //声明attribute变量a_Color,用来存放顶点颜色信息
      'attribute float a_Face;\n' + //声明attribute变量a_Face,用来存放方块表面的索引
      'uniform mat4 u_MvpMatrix;\n' + //声明uniform变量u_MvpMatrix,用来存放模型视图投影组合矩阵
      'uniform int u_PickedFace;\n' + //声明uniform变量u_PickedFace,用来存放选中表面的索引
      'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来向片元着色器传值顶点颜色信息

      'void main(){
    
    \n' +
      '  gl_Position = u_MvpMatrix * a_Position;\n' + //将模型视图投影组合矩阵与顶点坐标相乘赋值给顶点着色器内置变量gl_Position
      '  int face = int(a_Face);\n' +
      '  vec3 color = (face == u_PickedFace) ? vec3(1.0) : a_Color.rgb;\n' +
      '  if(u_PickedFace == 0) {
    
    \n' + // u_PickedFace == 0代表js程序中checkFace()获取像素颜色前给u_PickedFace变量传值0
      '    v_Color = vec4(color, a_Face/255.0);\n' + //将方块的表面编号赋值给RGBA的A分量即alpha
      '  } else {
    
    \n' +
      '    v_Color = vec4(color, a_Color.a);\n' + //将颜色赋值给v_Color
      '  }\n' +

      '}\n'

    //片元着色器
    var FSHADER_SOURCE = '' +
      '#ifdef GL_ES\n' +
      ' precision mediump float;\n' + // 设置精度
      '#endif\n' +
      'varying vec4 v_Color;\n' + //声明varying变量v_Color,用来接收顶点着色器传送的片元颜色信息
      'void main(){
    
    \n' +
      '  gl_FragColor = v_Color;\n' + //将顶点着色器传送的片元颜色赋值给内置变量gl_FragColor
      '}\n'

    //初始化着色器函数
    function initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE) {
    
    
      //创建顶点着色器对象
      var vertexShader = loadShader(gl, gl.VERTEX_SHADER, VSHADER_SOURCE)
      //创建片元着色器对象
      var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, FSHADER_SOURCE)

      if (!vertexShader || !fragmentShader) {
    
    
        return null
      }

      //创建程序对象program
      var program = gl.createProgram()
      if (!gl.createProgram()) {
    
    
        return null
      }
      //分配顶点着色器和片元着色器到program
      gl.attachShader(program, vertexShader)
      gl.attachShader(program, fragmentShader)
      //链接program
      gl.linkProgram(program)

      //检查程序对象是否连接成功
      var linked = gl.getProgramParameter(program, gl.LINK_STATUS)
      if (!linked) {
    
    
        var error = gl.getProgramInfoLog(program)
        console.log('程序对象连接失败: ' + error)
        gl.deleteProgram(program)
        gl.deleteShader(fragmentShader)
        gl.deleteShader(vertexShader)
        return null
      }
      //使用program
      gl.useProgram(program)
      gl.program = program
      //返回程序program对象
      return program
    }

    function loadShader(gl, type, source) {
    
    
      // 创建顶点着色器对象
      var shader = gl.createShader(type)
      if (shader == null) {
    
    
        console.log('创建着色器失败')
        return null
      }

      // 引入着色器源代码
      gl.shaderSource(shader, source)

      // 编译着色器
      gl.compileShader(shader)

      // 检查顶是否编译成功
      var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
      if (!compiled) {
    
    
        var error = gl.getShaderInfoLog(shader)
        console.log('编译着色器失败: ' + error)
        gl.deleteShader(shader)
        return null
      }

      return shader
    }

    function init() {
    
    
      //通过getElementById()方法获取canvas画布
      var canvas = document.getElementById('webgl')
      //通过方法getContext()获取WebGL上下文
      var gl = canvas.getContext('webgl')
      //初始化着色器
      if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    
    
        console.log('初始化着色器失败')
        return
      }

      // 设置canvas的背景色
      gl.clearColor(0.0, 0.0, 0.0, 1.0)

      //初始化顶点坐标和顶点颜色
      var n = initVertexBuffers(gl)

      setMatrixAndDraw(gl, n, canvas)

    }

    //设置矩阵并绘图
    function setMatrixAndDraw(gl, n, canvas) {
    
    

      //开启隐藏面消除
      gl.enable(gl.DEPTH_TEST)

      //清空颜色和深度缓冲区
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

      //获取顶点着色器uniform变量u_MvpMatrix、u_PickedFace的存储地址
      var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix')
      var u_PickedFace = gl.getUniformLocation(gl.program, 'u_PickedFace')
      if (!u_MvpMatrix || !u_PickedFace) {
    
    
        console.log('获取uniform变量u_MvpMatrix或u_PickedFace的存储地址失败')
        return
      }

      //创建视图投影矩阵
      var viewProjMatrix = new Matrix4()
      viewProjMatrix.setPerspective(30.0, canvas.width / canvas.height, 1.0, 100.0)
      viewProjMatrix.lookAt(0.0, 0.0, 7.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)

      gl.uniform1i(u_PickedFace, -1) //给顶点着色器uniform变量u_PickedFace传值-1 表示没有方块表面选中

      var currentAngle = 0.0 // 当前旋转的角度
      //注册鼠标点击事件
      canvas.onmousedown = function (ev) {
    
    
        var x = ev.clientX
        var y = ev.clientY
        var rect = ev.target.getBoundingClientRect()
        if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
    
    
          //获取点击位置在canvas坐标系中的值
          var x_in_canvas = x - rect.left
          var y_in_canvas = rect.bottom - y
          var face = checkFace(gl, n, x_in_canvas, y_in_canvas, currentAngle, u_PickedFace, viewProjMatrix,
            u_MvpMatrix)
          gl.uniform1i(u_PickedFace, face) //给顶点着色器uniform变量u_PickedFace传值选中表面索引
          draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)

        }
      }

      var tick = function () {
    
     //动画循环
        currentAngle = getCurrentAngle(currentAngle)
        draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)
        requestAnimationFrame(tick, canvas)
      }
      tick()
    }

    //初始化顶点坐标和顶点颜色
    function initVertexBuffers(gl) {
    
    

      var v0 = [1.0, 1.0, 1.0]
      var v1 = [-1.0, 1.0, 1.0]
      var v2 = [-1.0, -1.0, 1.0]
      var v3 = [1.0, -1.0, 1.0]
      var v4 = [1.0, -1.0, -1.0]
      var v5 = [1.0, 1.0, -1.0]
      var v6 = [-1.0, 1.0, -1.0]
      var v7 = [-1.0, -1.0, -1.0]

      //顶点
      var vertices = new Float32Array([
        ...v0, ...v1, ...v2, ...v3, // 前
        ...v0, ...v3, ...v4, ...v5, // 右
        ...v0, ...v5, ...v6, ...v1, // 上
        ...v1, ...v6, ...v7, ...v2, // 左
        ...v7, ...v4, ...v3, ...v2, // 下
        ...v4, ...v7, ...v6, ...v5 // 后
      ])

      var fontColor = [0.2, 0.58, 0.82]
      var backColor = [0.73, 0.82, 0.93]
      var leftColor = [0.78, 0.69, 0.84]
      var rightColor = [0.5, 0.41, 0.69]
      var topColor = [0.0, 0.32, 0.61]
      var downColor = [0.32, 0.18, 0.56]
      // 顶点的颜色
      var colors = new Float32Array([
        ...fontColor, ...fontColor, ...fontColor, ...fontColor, // v0-v1-v2-v3 前
        ...rightColor, ...rightColor, ...rightColor, ...rightColor, // v0-v3-v4-v5 右
        ...topColor, ...topColor, ...topColor, ...topColor, // v0-v5-v6-v1 上
        ...leftColor, ...leftColor, ...leftColor, ...leftColor, // v1-v6-v7-v2 左
        ...downColor, ...downColor, ...downColor, ...downColor, // v7-v4-v3-v2 下
        ...backColor, ...backColor, ...backColor, ...backColor, // v4-v7-v6-v5 后
      ])

      //方块表面
      var faces = new Uint8Array([
        1, 1, 1, 1, // v0-v1-v2-v3 前
        2, 2, 2, 2, // v0-v3-v4-v5 右
        3, 3, 3, 3, // v0-v5-v6-v1 上
        4, 4, 4, 4, // v1-v6-v7-v2 左
        5, 5, 5, 5, // v7-v4-v3-v2 下
        6, 6, 6, 6, // v4-v7-v6-v5 后
      ])
      // 绘制的索引
      var indices = new Uint8Array([
        0, 1, 2, 0, 2, 3, // 前
        4, 5, 6, 4, 6, 7, // 右
        8, 9, 10, 8, 10, 11, // 上
        12, 13, 14, 12, 14, 15, // 左
        16, 17, 18, 16, 18, 19, // 下
        20, 21, 22, 20, 22, 23 // 后
      ])

      if (!initArrayBuffer(gl, vertices, 3, gl.FLOAT, 'a_Position')) {
    
    
        return -1
      }

      if (!initArrayBuffer(gl, colors, 3, gl.FLOAT, 'a_Color')) {
    
    
        return -1
      }
      if (!initArrayBuffer(gl, faces, 1, gl.UNSIGNED_BYTE, 'a_Face')) {
    
    
        return -1
      }

      //创建缓冲区对象
      var indexBuffer = gl.createBuffer()

      //将顶点索引写入缓冲区对象
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer)
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW)

      return indices.length

    }

    function checkFace(gl, n, x, y, currentAngle, u_PickedFace, viewProjMatrix, u_MvpMatrix) {
    
    
      var pixels = new Uint8Array(4) //创建Uint8Array类型化数组,接收获取的像素值数据
      gl.uniform1i(u_PickedFace, 0) //给顶点着色器uniform变量u_PickedFace传值0
      draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix)
      //读取鼠标点击位置像素颜色信息,pixels[3]为方块表面索引
      gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels)

      return pixels[3] //将pixels[3]即RGBA值的A值返回
    }

    var g_MvpMatrix = new Matrix4() //模型视图投影矩阵 
    function draw(gl, n, currentAngle, viewProjMatrix, u_MvpMatrix) {
    
    
      //计算模型视图投影矩阵 
      g_MvpMatrix.set(viewProjMatrix)
      g_MvpMatrix.rotate(currentAngle, 1.0, 0.0, 0.0)
      g_MvpMatrix.rotate(currentAngle, 0.0, 1.0, 0.0)
      g_MvpMatrix.rotate(currentAngle, 0.0, 0.0, 1.0)

      //模型视图投影矩阵的计算结果传给uniform变量u_MvpMatrix
      gl.uniformMatrix4fv(u_MvpMatrix, false, g_MvpMatrix.elements)

      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
      gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0) //绘图
    }

    var g_LastTime = Date.now() // 上次绘制的时间
    var ANGLE_SET = 30.0 // 旋转速度(度/秒)
    function getCurrentAngle(angle) {
    
    
      var now = Date.now()
      var elapsed = now - g_LastTime //上次调用与当前时间差
      g_LastTime = now
      var newAngle = angle + (ANGLE_SET * elapsed) / 1000.0
      return newAngle %= 360
    }

    function initArrayBuffer(gl, data, num, type, attribute) {
    
    
      //创建缓冲区对象
      var buffer = gl.createBuffer()
      //将顶点坐标和顶点颜色信息写入缓冲区对象
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
      gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW)

      //获取顶点着色器attribute变量存储地址, 分配缓存并开启
      var a_Attribute = gl.getAttribLocation(gl.program, attribute)
      gl.vertexAttribPointer(a_Attribute, num, type, false, 0, 0)
      gl.enableVertexAttribArray(a_Attribute)

      return true
    }

    init()
  </script>
</body>

</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/aa2528877987/article/details/132146478