本系列教程主要讲解利用WebGL开发网页版的三维图形程序。这里主要用到的OpenGL和FlyMath内容。本系列内容较难。要求学生对几何和编程有一定的了解。建议初三以上同学学习。
屏幕上一个点就是一个像素。像素是方形。在WEBGL中我们可以把点设置成圆形。我们来看下例子:
javascript部分源码
//绘制圆形
function draw_point()
{
//清空canvas的颜色
gl_context.clearColor(0,0,0.5,1);
//清空webgl颜色缓冲区和深度缓冲区里的内容
gl_context.clear(gl_context.COLOR_BUFFER_BIT | gl_context.DEPTH_BUFFER_BIT);
//定义顶点shader和片断shader
var vs_src = "attribute vec4 a_Position;\n" +
"void main() {\n" +
"gl_Position = a_Position;\n"+
"gl_PointSize = 100.0;\n" +
"}\n";
var fs_src = "precision highp float;\n" +
"void main() {\n" +//每个点的中心坐标都是(0.5,0.5)
" float dist = distance(gl_PointCoord,vec2(0.5,0.5));\n" +
" if(dist < 0.5){\n" +
" gl_FragColor = vec4(1,1,0,1);\n" +
" } else { discard;}\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)){
show_err();
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)){
show_err();
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)) {
show_err();
return;
}
//绑定shader中的参数变量
var shader_pos = gl_context.getAttribLocation(shaderProgram, "a_Position");
var vertices = new Float32Array([-0.2,0.0]);
var point_buf = gl_context.createBuffer();
//使用选择的程序,激活缓冲区,渲染
gl_context.useProgram(shaderProgram);
gl_context.enableVertexAttribArray(shader_pos);
gl_context.bindBuffer(gl_context.ARRAY_BUFFER, point_buf);
gl_context.bufferData(gl_context.ARRAY_BUFFER, new Float32Array(vertices), gl_context.STATIC_DRAW);
gl_context.vertexAttribPointer(shader_pos, 2, gl_context.FLOAT, false, 0, 0);
gl_context.drawArrays(gl_context.POINTS,0,1);
}