我会持续更新关于wegl的编程指南中的代码。
当前的代码不会使用书中的缩写,每一步都是会展开写。希望能给后来学习的一些帮助
本章节中我我们学习使用buffer传递数据
- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- head>
-
- <body>
-
- <canvas id='canvas'>canvas>
- <script>
- let canvas = document.getElementById('canvas');
- let gl = canvas.getContext('webgl');
- //顶点着色器
- let vertexShaderSource = `
- attribute vec2 a_Position;
- attribute float a_PointSize;
- void main(){
- gl_Position = vec4(a_Position,0.0,1.0) ;
- gl_PointSize = a_PointSize;
- }
- `
- //片元着色器
- let fragmentShaderSouce = `
- precision mediump float;
- void main(){
- gl_FragColor = vec4(1.0,0.0,0.0,1.0);
- }
- `
- // 创建顶点着色器
- let vertexShader = gl.createShader(gl.VERTEX_SHADER);
- gl.shaderSource(vertexShader, vertexShaderSource)
- gl.compileShader(vertexShader)
- //创建片元着色器
- let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
- gl.shaderSource(fragmentShader, fragmentShaderSouce)
- gl.compileShader(fragmentShader)
- //创建渲染程序
- let program = gl.createProgram();
- gl.attachShader(program, vertexShader);
- gl.attachShader(program, fragmentShader);
- gl.linkProgram(program);
- //使用当前渲染程序
- gl.useProgram(program)
-
-
- //检查片元着色器的是否正确
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- throw gl.getProgramInfoLog(program);
- }
- //三角形的坐标
- let positonArray = new Float32Array([
- 0.5, 0.5,
- -0.5, -0.5,
- 0.5, -0.5,
- -0.5, 0.5])
- //每个坐标点但的大小
- let sizeArray = new Float32Array([10.0, 20.0, 30.0,40.0])
- //位置坐标变量
- let a_Position = gl.getAttribLocation(program, 'a_Position');
- //点的大小
- let a_PointSize = gl.getAttribLocation(program, 'a_PointSize')
-
- //创建坐标的buffer
- let buffer = gl.createBuffer();
- //绑定buffer
- gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
- //将三角形的坐标数据放入缓冲区
- gl.bufferData(gl.ARRAY_BUFFER, positonArray, gl.STATIC_DRAW)
- // a_Position 赋值
- gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
- // 使能顶点位置
- gl.enableVertexAttribArray(a_Position);
-
- //创建顶点大小的buffer
- let pointSizeBuffer = gl.createBuffer();
- //绑定buffer
- gl.bindBuffer(gl.ARRAY_BUFFER, pointSizeBuffer);
- // 将点的大小数据放入缓冲区
- gl.bufferData(gl.ARRAY_BUFFER,sizeArray,gl.STATIC_DRAW);
- // a_PointSize 赋值
- gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false, 0, 0)
- // 使能顶点大小
- gl.enableVertexAttribArray(a_PointSize);
- //绘制
- gl.clearColor(0.0, 0.0, 0.0, 1.0);
- gl.clear(gl.COLOR_BUFFER_BIT);
- //绘制点 从第0个开始,绘制4次
- gl.drawArrays(gl.POINTS, 0, 4)
-
- script>
- body>
-
- html>