Bootstrap

WebGL-12.颜色混合

本系列教程主要讲解利用WebGL开发网页版的三维图形程序。这里主要用到的OpenGL和FlyMath内容。本系列内容较难。要求学生对几何和编程有一定的了解。建议初三以上同学学习。

颜色混合是指在WebGL里,我们可以对两个物品的渲染效果进行处理,处理效果就像Photoshop里那样的图像混合处理。混合计算可分为Alpha混合和Color混合。前者是带Alpha属性。

WebGL里的混合计算主要分两步:

1.开启混合功能

gl_context.enable(gl_context.BLEND);

2.指定混合函数

gl_context.blendFunc(src_factor,dst_factor);
 
#混合后的颜色 = 源颜色 * src_factor + 目标颜色 * dst_factor
#源颜色指将要画上去的物体颜色。目标颜色指屏幕上已经有了的颜色。

WebGL支持的src_factor和dst_factor主要有以下几种参数:

GL_ZERO: 表示使用0.0作为因子。
GL_ONE: 表示使用1.0作为因子。
GL_SRC_ALPHA:表示使用源颜色的alpha值来作为因子。
GL_DST_ALPHA:表示使用目标颜色的alpha值来作为因子。
GL_ONE_MINUS_SRC_ALPHA:表示用1.0减去源颜色的alpha值来作为因子。
GL_ONE_MINUS_DST_ALPHA:表示用1.0减去目标颜色的alpha值来作为因子。
GL_SRC_COLOR:把源颜色的四个分量分别作为因子的四个分量。
GL_DST_COLOR:把目标颜色的四个分量分别作为因子的四个分量。
GL_ONE_MINUS_SRC_COLOR、 GL_ONE_MINUS_DST_COLOR:分别指(1-源颜色的alpha 和 1-目标颜色的alpha)

利用这样运算我们可以生成各种好看的效果。这节我们演示一个很简单的例子。一前一后两个正方形。两个正方形都是用同一张纹理(带alpha)。第一张纹理不作任何混合计算;第二张纹理用GL_DST_COLOR。大家想想会有什么效果?

javascript部分源码

//定义全局GL上下文
var gl_context;
     
//循环控制参数
var curTime;
var isStop=1;
    
//偏移步长
var cur_x = 0;
var x_step = 0.01;
     
//定义Camera位置
var camera = [0,0,1];
var camera_to = [0,0,0];
var camera_up = [0,1,0];
     
//定义颜色数组
var color = [1,0,0];
    
//定义camera矩阵和工程矩阵
var matView = new Array;
var matProject = new Array;
     
//定义纹理图片
var curImg;
var imgSrc = "webgl.png";
     
//时间函数
function onTime()
{
    cur_x += x_step;
        
    if(cur_x>0.5 || cur_x<-0.5)
        x_step *=-1;
        
    draw_quad();  
    curTime = setTimeout("onTime()",100);
}
      
//处理点击事件
function click(ev)
{
    if(isStop==1)
        isStop=0;
    else
        isStop=1;
          
    if(isStop==0)
        onTime();
    else
        clearTimeout(curTime);
}
     
//加载纹理图片
function pre_loadImg()
{ 
    curImg = new Image();
    curImg.src = imgSrc;
         
    curImg.onload = function()
    {
        draw_quad();
        return;
    }
         
    curImg.onerror = function()
    {
        alert("加载纹理图片失败!");
        return;
    }   
}
     
//初始化WebGL
function init_webgl()
{
  var canvas = document.getElementById("webGL");
       
  if(!canvas){
    alert("获取<Canvas>标签失败!");
    return;
}
     
  //获取webGL统计图上下文
  gl_context = canvas.getContext('webgl',
                { antialias:true,
                                  depth:true,
                  stencil:true});
     
  if(!gl_context){
    alert("获取WebGL上下文失败!");
    return;
  }
     
  canvas.width = $("#area").width();
  canvas.height = $("#area").width()*3/5;
       
  canvas.onmousedown = function(ev){ click(ev);}
     
  //设置视口大小
  gl_context.viewport(0,0,canvas.width,canvas.height);
     
  //设置matView和matProject矩阵
  FlyMath.Matrix.LookAtRH(matView,camera,camera_to,camera_up);
  FlyMath.Matrix.PerspectiveRH(matProject,FlyMath_PI/3,1,1,100);
     
  pre_loadImg();
}
     
//绘制正方形
function draw_quad()
{
//清空canvas的背景颜色
  gl_context.clearColor(0,0,0.5,1);
     
  //清空webgl颜色缓冲区和深度缓冲区里的内容
  gl_context.clear(gl_context.COLOR_BUFFER_BIT | gl_context.DEPTH_BUFFER_BIT);
  //开启深度缓冲检测
  gl_context.enable(gl_context.DEPTH_TEST);
     
//定义顶点shader和片断shader
    var vs_src = "attribute vec4 a_Position;\n" +
                "attribute vec2 a_UV;\n" +
                "uniform mat4 projectionMatrix;\n" +
                "uniform mat4 modelViewMatrix;\n" +
                "uniform mat4 offsetMatrix;\n" +
                "varying vec2 A_UV;\n" +             
                "void main() {\n" +
                    "gl_Position = projectionMatrix * modelViewMatrix * offsetMatrix * a_Position;\n"+
                    "A_UV = a_UV;\n" +
                    "}\n";
     
    var fs_src = "precision highp float;\n" +
                "varying vec2 A_UV;\n" +
                "uniform sampler2D A_Texture;\n" +
                "void main() {\n" +
                " vec4 imgColor = texture2D(A_Texture,A_UV);\n" +
                " gl_FragColor = imgColor;\n" +
                "}\n";
                    
    var vs = gl_context.createShader(gl_context.VERTEX_SHADER);
    gl_context.shaderSource(vs,vs_src);
    gl_context.compileShader(vs);
       
    if(!gl_context.getShaderParameter(vs,gl_context.COMPILE_STATUS)){
        alert(gl_context.getShaderInfoLog(vs));
        return;
    }
     
    var fs = gl_context.createShader(gl_context.FRAGMENT_SHADER);
    gl_context.shaderSource(fs,fs_src);
    gl_context.compileShader(fs);
       
    if(!gl_context.getShaderParameter(vs,gl_context.COMPILE_STATUS)){
        alert(gl_context.getShaderInfoLog(fs));
        return;
    }
     
//加载选择的顶点和片断
    var shaderProgram = gl_context.createProgram();
    gl_context.attachShader(shaderProgram, vs);
    gl_context.attachShader(shaderProgram, fs);
    gl_context.linkProgram(shaderProgram);
     
    if (!gl_context.getProgramParameter(shaderProgram, gl_context.LINK_STATUS)) {
        alert("Could not initialise shaders");
        return;
    }
     
//绑定shader中的参数变量
    var shader_pos = gl_context.getAttribLocation(shaderProgram, "a_Position");
    var shader_uv = gl_context.getAttribLocation(shaderProgram, "a_UV");
    
    var shaderModelViewMatrixUniform = gl_context.getUniformLocation(shaderProgram,"modelViewMatrix");
    var shaderProjectionMatrixUniform = gl_context.getUniformLocation(shaderProgram,"projectionMatrix");
    var shaderOffsetMatrixUniform = gl_context.getUniformLocation(shaderProgram,"offsetMatrix");
    var SamplerUniform = gl_context.getUniformLocation(shaderProgram,"A_Texture");
     
/* 正方形顶点位置
    0 , 1
    2 , 3 
*/
    var vertices = new Float32Array([-0.3,0.3,-1,0.3,0.3,-1,-0.3,-0.3,-1,0.3,-0.3,-1]);
    var indices =  [0,1,2,1,2,3];
    var uvs = [0,0,1,0,0,1,1,1];
    var matOffset = [];
    FlyMath.Matrix.Identity(matOffset);
     
    var quad_buf = gl_context.createBuffer();
    var indexBuffer = gl_context.createBuffer();
    var uvBuffer = gl_context.createBuffer();
                
//使用选择的程序,激活缓冲区,渲染
    gl_context.useProgram(shaderProgram);
    gl_context.enableVertexAttribArray(shader_pos);
    gl_context.enableVertexAttribArray(shader_uv);
     
    gl_context.bindBuffer(gl_context.ARRAY_BUFFER, quad_buf);
    gl_context.bufferData(gl_context.ARRAY_BUFFER, new Float32Array(vertices), gl_context.STATIC_DRAW);
    gl_context.vertexAttribPointer(shader_pos, 3, gl_context.FLOAT, false, 0, 0);
     
    gl_context.bindBuffer(gl_context.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl_context.bufferData(gl_context.ELEMENT_ARRAY_BUFFER, new Uint8Array(indices), gl_context.STATIC_DRAW);
         
    gl_context.bindBuffer(gl_context.ARRAY_BUFFER,uvBuffer);
    gl_context.bufferData(gl_context.ARRAY_BUFFER,new Float32Array(uvs),gl_context.STATIC_DRAW);
    gl_context.vertexAttribPointer(shader_uv, 2, gl_context.FLOAT, false, 0, 0);
     
//绑定矩阵
    gl_context.uniformMatrix4fv(shaderModelViewMatrixUniform,false,matView);
    gl_context.uniformMatrix4fv(shaderProjectionMatrixUniform,false,matProject);
    gl_context.uniformMatrix4fv(shaderOffsetMatrixUniform,false,matOffset);
         
//绑定纹理图片,设置纹理坐标方式
    var img_texture = gl_context.createTexture();
    gl_context.bindTexture(gl_context.TEXTURE_2D, img_texture);
    gl_context.texImage2D(gl_context.TEXTURE_2D, 0, gl_context.RGBA, gl_context.RGBA, gl_context.UNSIGNED_BYTE, curImg);
     
    gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MIN_FILTER, gl_context.NEAREST);
    gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_MAG_FILTER, gl_context.NEAREST);
    gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_S, gl_context.CLAMP_TO_EDGE);
    gl_context.texParameteri(gl_context.TEXTURE_2D, gl_context.TEXTURE_WRAP_T, gl_context.CLAMP_TO_EDGE);
         
    gl_context.activeTexture(gl_context.TEXTURE0);
    gl_context.bindTexture(gl_context.TEXTURE_2D, img_texture);
         
    gl_context.uniform1i(SamplerUniform, 0);
         
    //关闭混合功能 
    gl_context.disable(gl_context.BLEND);
    gl_context.drawElements(gl_context.TRIANGLES,indices.length,gl_context.UNSIGNED_BYTE, 0);
        
//设置第二个正方形的偏移矩阵
    FlyMath.Matrix.Identity(matOffset);
    FlyMath.Matrix.Translation(matOffset,cur_x,0.0,0.1);
    gl_context.uniformMatrix4fv(shaderOffsetMatrixUniform,false,matOffset);
        
    //开启混合功能
    gl_context.enable(gl_context.BLEND);
    //混合函数设置
    gl_context.blendFunc(gl_context.DST_COLOR,gl_context.ONE);
    gl_context.drawElements(gl_context.TRIANGLES,indices.length,gl_context.UNSIGNED_BYTE, 0); 
}

运行范例

;