index.html
<html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<title>colored triangle</title>
<script src="../lib/cuon-utils.js"></script>
<style>
body{
margin:0;
}
canvas{
display:block;
border:1px solid #999;
}
.btn-group {
width: 500px;
text-align: center;
padding: 10px 0;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script src="./index.js"></script>
index.js
/**
* 在webgl中 如果顶点着色器与片元着色器中有类型和名称都相同的varying变量,
* 那么顶点着色器赋值给该变量的值就会被自动的传入片元着色器
*/
// 顶点着色器程序
var VSHADER_SOURCE =`
attribute vec4 a_Position;
void main() {
//设置坐标
gl_Position = a_Position;
gl_PointSize = 30.0;
}
`;
// 片元着色器
var FSHADER_SOURCE =`
precision mediump float;
uniform float u_Width;
uniform float u_Height;
void main() {
//设置颜色
gl_FragColor = vec4(gl_FragCoord.x/u_Width, 0, gl_FragCoord.y/u_Height, 1.0);
}
`;
// 获取canvas元素
var canvas = document.getElementById('canvas');
// 获取绘制二维上下文
var gl = canvas.getContext('webgl');
gl.clearColor(0, 0, 0, 1);
// 初始化shader
initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);
// 初始化顶点
var n = initVertexBuffer(gl);
function draw(gl, n) {
console.log(n);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, n );
}
/**
* 初始化顶点
*/
function initVertexBuffer(gl) {
/* ==================== 创顶点坐标建缓冲区 ==================== */
var vertices = new Float32Array([
-0.5, 0,
0, 0.5,
0.5, 0,
]);
var size = 2;
var FSIZE = Float32Array.BYTES_PER_ELEMENT;
/* 创建缓冲区 */
var vertexPositionBuffer = gl.createBuffer();
// 将缓冲区绑定到目标
gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer);
// 向缓冲区写入数据
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
/* 设置顶点 */
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
// 将缓冲区对象分配给a_Position
gl.vertexAttribPointer(a_Position, size, gl.FLOAT, false, 0, 0);
// 激活attibue 是缓冲区对attribute变量分配生效
gl.enableVertexAttribArray(a_Position);
/* 设置 u_Width/u_Height 值 */
var u_Width = gl.getUniformLocation(gl.program, 'u_Width');
gl.uniform1f(u_Width, canvas.width);
var u_Height = gl.getUniformLocation(gl.program, 'u_Height');
gl.uniform1f(u_Height, canvas.height);
return vertices.byteLength / size / FSIZE;
}
draw(gl, n);
以下函数详见 https://www.jianshu.com/p/c33a36c26c06
<script src="../lib/cuon-utils.js"></script>
colored-triangle.png
网友评论