index.html
<html>
<head>
<meta lang="en">
<meta charset="UTF-8">
<title>varying colored points</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;
attribute vec4 a_Color;
varying vec4 v_Color;
void main() {
//设置坐标
gl_Position = a_Position;
gl_PointSize = 30.0;
v_Color = a_Color;
}
`;
// 片元着色器
var FSHADER_SOURCE =`
precision mediump float;
varying vec4 v_Color;
void main() {
//设置颜色
gl_FragColor = v_Color;
}
`;
// 获取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) {
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.POINTS, 0, n );
}
/**
* 初始化顶点
*/
function initVertexBuffer(gl) {
/* ==================== 创顶点坐标建缓冲区 ==================== */
var vertices = new Float32Array([
-0.5, 0, 1, 0, 0,
0, 0.5, 0, 1, 0,
0.5, 0, 0, 0, 1,
]);
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, FSIZE * 5, 0);
// 激活attibue 是缓冲区对attribute变量分配生效
gl.enableVertexAttribArray(a_Position);
/* 设置颜色 */
var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
// 将缓冲区对象分配给a_Position
gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 5, FSIZE * 2);
// 激活attibue 是缓冲区对attribute变量分配生效
gl.enableVertexAttribArray(a_Color);
return vertices.byteLength / size / FSIZE;
}
draw(gl, n);
以下函数详见 https://www.jianshu.com/p/c33a36c26c06
<script src="../lib/cuon-utils.js"></script>
colored-points.png
网友评论