示例:在屏幕显示一个矩形
<!DOCTYPE HTML>
<head>
</head>
<html>
<body onload="main()">
<canvas id="webgl" width="500" height="500" style="border: 1px solid #ff0000;">
</canvas>
<script type="text/javascript">
//顶点着色器程序
var VSHADER_SOURCE =
'attribute vec4 a_Position;'+
'void main(){\n'+
'gl_Position = a_Position;\n'+
'}\n';
//片元着色器程序
var FSHADER_SOURCE =
'void main(){'+
'gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n'+
'}\n';
function main(){
//获取<canvas>元素
var canvas = document.getElementById("webgl");
if(!canvas){
console.log('error');
return;
}
//获取绘制三维图形的绘图上下文
var gl = canvas.getContext('webgl');
// 创建着色器对象
const fShader = gl.createShader(gl.FRAGMENT_SHADER);
const vShader = gl.createShader(gl.VERTEX_SHADER);
// 将着色器源码写入对象
gl.shaderSource(vShader, VSHADER_SOURCE);
gl.shaderSource(fShader, FSHADER_SOURCE);
// 编译着色器
gl.compileShader(vShader);
gl.compileShader(fShader);
// 创建程序
const program = gl.createProgram();
// 程序绑定着色器
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
// 链接程序
gl.linkProgram(program);
// 使用程序
gl.useProgram(program);
var n = initVertexBuffers(gl);
if(n < 0){
console.log('Failed to set positions of vertices');
return;
}
gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
function initVertexBuffers(gl){
var vertices = new Float32Array([-0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, -0.5]); //坐标点位置
var n = 4; //坐标点个数
//创建缓冲区对象
var vertexBuffer = gl.createBuffer();
if(!vertexBuffer){
console.log('Failed to create the buffer object');
return -1;
}
//将缓冲区对象绑定到目标
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
//向缓冲区对象中写入数据
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(program, 'a_Position');
if(a_Position < 0){
console.log('Failed to get the storage location of a_Position');
return;
}
//将缓冲区对象分配给a_Position变量
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
//连接a_Position变量与分配给它的缓冲区对象
gl.enableVertexAttribArray(a_Position);
return n;
}
}
</script>
</body>
</html>