需要源码可以Q群:828202939 或者点击这里 希望可以和大家一起学习、一起进步!!纯手打!!
如有错别字或有理解不到位的地方,可以留言或者加微信15250969798,在下会及时修改!!!!!
上节课主要的怎么利用gl.drawArryas这个函数来绘制一些基本的图形,那么对于复杂的图形我们怎么处理呢?
比如说游戏里面的人物,对于webgl而言,它就是由很多三角形的面组成的图形
下面我们来看看矩形的绘制是怎么回事,这是我们第一个比基础图像复杂的图形
这其实是2个三角形组成的图形,你可以尝试着改下顶点的位置或者绘制的方式,会渲染出很多有趣的图形
上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>绘制矩形</title>
</head>
<body onload="main()">
<canvas id="webgl" width="400" height="400">
Please use a browser that supports "canvas"
</canvas>
<script src="../lib/webgl-utils.js"></script>
<script src="../lib/webgl-debug.js"></script>
<script src="../lib/cuon-utils.js"></script>
<script src="HelloQuad.js"></script>
</body>
</html>
//顶点着色器
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
'}\n';
// 片元着色器
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n' +
'}\n';
function main() {
// 获取元素
var canvas = document.getElementById('webgl');
// 获取上下文
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
//初始化
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to intialize shaders.');
return;
}
// 设置顶点位置
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
// 设置背景色
gl.clearColor(0, 0, 0, 1);
// 清空 <canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
// 绘制三角形带
gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
}
//这里设置的是点的位置,本例设置为矩形,如果设置为
//-0.8, 0.5, -0.5, -0.5, 0.8, 0.5, 0.5, -0.5渲染出来的是一个倒梯形
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; // The number of vertices
// 创建缓冲区对象
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);
//获取attribute的位置
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
// 将缓冲区对象分配给attribute变量,这里只有平面的顶点xy,所谓分量为2,第三四分量会默认为0.0,1.0
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
// 开始attribute变量
gl.enableVertexAttribArray(a_Position);
return n;
}
展示结果:
如果把
改成gl.drawArrays(gl.TRIANGLE_FAN, 0, n);
运行结果如下: