# WebGL 绘制一个三角形
# WebGL Startup
创建 WebGL 上下文
const canvas=document.querySelector('canvas');
const gl=canvas.getContext('webgl');
特性检测方式 (考虑兼容)
function create3DContext(canvas,options){
const names=['webgl'],'experimental-webgl','webkit-3d','moz-webgl'];
if(options.webgl2) names.unshift('webgl2');
let context=null;
for(let ii=0;ii<names.length;++ii){
try{
context=canvas.getContext(names[ii],options);
} catch(e){
// no-empty
}
if(context){
break;
}
}
return context;
}
创建 WebGL Program
顶点着色器 (Vertex Shader)
attribute vec2 position; void main(){ gl_PointSize = 1.0; //默认1px gl_Positon = vec(position,1.0,1.0) //四维坐标 }
片元着色器 (Framgment Shader)
precision medium float void main(){ gl_FragColor =vec4(1.0,0.0,0.0,1.0)//(r,g,b,a)取值是归一化的 0~1, }
创建 program
const vertexShader=gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader,vertex);
gl.compileShader(vertexShader);
const fragmentShader=gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader,vertex);
gl.compileShader(fragmentShader);
const program=gl.createProgram();
gl.attachShader(program,vertexShader);
gl.attachShader(program,fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
将数据存入缓冲区 (Data to Frame Buffer)
三个顶点坐标
const points=new Float32Array({
-1,-1,
0,1,
1,-1
})
const bufferId=gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,bufferId);
gl.bufferData(gl.ARRAY_BUFFER,points,gl.STATIC_DRAW);
将缓冲区数据读取到 GPU (Frame Buffer to GPU)
const vPosition = gl.getAttribLocation(program,'position');// 获取顶点着色器中的 position 变量的地址
gl.vertexAttrPotinter(vPosition,2,gl.FLOAT,FALSE,0,0);// 设置变量长度和类型
gl.enableVertexAttribArray(vPosition);
GPU 执行 WebGL 程序,输出 Output
l.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES,0,points.length/2)