在前一篇的基础上做了以下修改
[1]shader改为从url中获取
[2]去掉了四个顶点颜色的输入,改为根据顶点同左下角的距离在fragment shader中计算着色.
现在有四个源文件组成这个demo
html文件
<html>
<head>
<!--
Date: 2018-3-19
Author: kagula
Prologue:
WebGL2的例子
Prologue:
Description:
显示一个左下角红色,右上角白色的rectangle.
Original:
[1]https://my.oschina.net/thesadabc/blog/1592866
測試環境
[1]Chrome 65.0.3325.162
[2]nginx 1.12.2
-->
<title>第二个Webgl2程序</title>
<meta charset="utf-8">
<!-- gl-matrix version 2.4.0 from http://glmatrix.net/ -->
<script type="text/javascript" src="/gl-matrix-min.js"></script>
<script type="text/javascript" src="/kagula/webgl2_helper.js"></script>
</head>
<body>
<canvas id="glCanvas" width="320" height="200"></canvas>
</body>
</html>
<script>
main();
//弄4个顶点, 4個顔色, 用来演示render流程!
function initBuffers(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the square.
//WebGL最后会把计算好的图像信息投影到左下角{-1,-1},右上角{1,1}的区域中。
const positions = [
1.0, 1.0,
-1.0, 1.0,
1.0, -1.0,
-1.0, -1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER,
new Float32Array(positions),
gl.STATIC_DRAW);
return {
position: positionBuffer
};
}
async function main() {
//选择器的使用
//http://www.runoob.com/jsref/met-document-queryselector.html
const canvas = document.querySelector("#glCanvas");
// Initialize the GL context
//為了获取WebGL2上下文,getContext方法传入的参数是"webgl2",而不是"webgl".
const gl = canvas.getContext("webgl2");
// Only continue if WebGL is available and working
if (!gl) {
alert("Unable to initialize WebGL. Your browser or machine may not support it.");
return;
}
//OpenGL ES 3.0 不支持多维数组
//對傳入的數組大小有限制
console.log("gl.MAX_VERTEX_UNIFORM_VECTORS=" + gl.MAX_VERTEX_UNIFORM_VECTORS + ", gl.MAX_FRAGMENT_UNIFORM_VECTORS=" + gl.MAX_FRAGMENT_UNIFORM_VECTORS);
//装配shader到shaderProgram中去
const vsSource = await loadResource("../shader/simple.vs");
const fsSource = await loadResource("../shader/simple.fs");
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
//为了让外部的数据能统一传到shanderProgram中去,新建programInfo对象。
//vertexPosition => aVertexPosition位置
//projectionMatrix => uProjectionMatrix位置
//modelViewMatrix => uModelViewMatrix位置
//...
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
out_vpos: gl.getAttribLocation(shaderProgram, 'out_vpos'),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
},
};
//initBuffers(gl)返回要render的vertex.
drawScene(gl, programInfo, initBuffers(gl));
}//main
</script>
webgl2_helper.js文件
async function loadResource(remoteFile) {
try {
let response = await fetch(remoteFile);
return response.text();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}
}
// Initialize a shader program, so WebGL knows how to draw our data
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
// creates a shader of the given type, uploads the source and
// compiles it.
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
function drawScene(gl, programInfo, buffers) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = 45 * Math.PI / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix,
fieldOfView,
aspect,
zNear,
zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -3.0]); // amount to translate, [-0.0, 0.0, -6.0] 放到远一点
//這裏準備vertex shader需要的數據
//整個pipeline可以看成下面的流程
//我們使用WebGL準備數據 => Vertex Shader => WebGL => Fragment Shader => WebGL => Canvas
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
{
// gl.ARRAY_BUFFER => 指向 => buffers.position
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
//指定源数据格式.
//https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
2,// pull out 2 values per iteration //Must be 1, 2, 3, or 4. 比如说顶点{x,y}要选2,{x,y,z}要选3,颜色{r,g,b,a}要选4
gl.FLOAT,// the data in the buffer is 32bit floats
false,// don't normalize
0,//stride, how many bytes to get from one set of values to the next
0);//how many bytes inside the buffer to start from
//源数据填充到gl
//tell WebGL that this attribute should be filled with data from our array buffer.
//gl.ARRAY_BUFFER => 数据传到 => programInfo.attribLocations.vertexPosition
gl.enableVertexAttribArray(
programInfo.attribLocations.vertexPosition);
}
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
//projectionMatrix => programInfo.uniformLocations.projectionMatrix
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,//A GLboolean specifying whether to transpose the matrix. Must be false.
projectionMatrix);
//modelViewMatrix => programInfo.uniformLocations.modelViewMatrix
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix);
//數據準備好后可以draw了.
{
const offset = 0;
const vertexCount = 4;
//开始处理已经在gl中的顶点数据
//gl.TRIANGLE_STRIP模式復用前面兩個頂點, 所以這裏告訴gl, render兩個三角形.
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
}
}
vertex shader文件simple.vs
#version 300 es
//指定float int的精度
precision highp float;
precision highp int;
//從設備外部传入的數據.
in vec4 aVertexPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
//這裏存放要傳給Fragment shader的數據.
out vec2 frag_vpos;
void main() {
float curX = (aVertexPosition.x + 1.) / 2.;
float curY = (aVertexPosition.y + 1.) / 2.;
frag_vpos = vec2(curX, curY);
//output vertex position to pipeline
//通过透视投影的方式,转3D属性的顶点映射成2D属性的顶点。
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
}
fragment shader文件simple.fs
#version 300 es
precision highp float;
//from vertex shader
in vec2 frag_vpos;
//output to pipeline
out vec4 myOutputColor;
void main() {
float pos_x = frag_vpos.x;
float pos_y = frag_vpos.y;
float distance = sqrt(pos_x * pos_x + pos_y * pos_y);
//第四个参数为Alpha通道,1=>红色 ,0=>白色, 所以左下角最红
myOutputColor = vec4(1, 0, 0, 1. - distance);
}