代码如下:
<!DOCTYPE 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>Document</title><script src="js/glMatrix-0.9.6.min.js"></script><script>//顶点着色器let vertexstring = `attribute vec4 a_position;uniform mat4 proj;void main(void){gl_Position =proj * a_position;gl_PointSize=60.0;}`;//片元着色器let fragmentstring = `void main(void){gl_FragColor = vec4(0,0,1.0,1.0);}`;var projMat4 = mat4.create();var webgl;//function init() {initWebgl();initShader();initBuffer();draw();}//webgl初始化function initWebgl() {//获取webgl的容器对象let webglDiv = document.getElementById('myCanvas');//获取webGL对象webgl = webglDiv.getContext("webgl");//webGL视觉区域webgl.viewport(0, 0, webglDiv.clientWidth, webglDiv.clientHeight);//设置webgl投影坐标系mat4.ortho(0, webglDiv.clientWidth, webglDiv.clientHeight, 0, -1.0, 1.0, projMat4)}//Shader初始化function initShader() {//定义Shader//顶点shaderlet vsshader = webgl.createShader(webgl.VERTEX_SHADER);//片元shaderlet fsshader = webgl.createShader(webgl.FRAGMENT_SHADER);// 绑定shaderwebgl.shaderSource(vsshader, vertexstring);webgl.shaderSource(fsshader, fragmentstring);// 编译shaderwebgl.compileShader(vsshader);webgl.compileShader(fsshader);if (!webgl.getShaderParameter(vsshader, webgl.COMPILE_STATUS)) {var err = webgl.getShaderInfoLog(vsshader);alert(err);return;}if (!webgl.getShaderParameter(fsshader, webgl.COMPILE_STATUS)) {var err = webgl.getShaderInfoLog(fsshader);alert(err);return;}//创建shaderlet program = webgl.createProgram();//着色器绑定shaderwebgl.attachShader(program, vsshader);webgl.attachShader(program, fsshader)webgl.linkProgram(program);webgl.useProgram(program);webgl.program = program}//Buffer初始化 将数据绑定到shaderfunction initBuffer() {let pointPosition = new Float32Array([100.0, 100.0, 0.0, 1.0]);let aPsotion = webgl.getAttribLocation(webgl.program, "a_position");webgl.vertexAttrib4fv(aPsotion, pointPosition);let uniformProj = webgl.getUniformLocation(webgl.program, "proj");webgl.uniformMatrix4fv(uniformProj, false, projMat4);}//webgl绘制function draw() {webgl.clearColor(0.0, 0.0, 0.0, 1.0);webgl.clear(webgl.COLOR_BUFFER_BIT | webgl.DEPTH_BUFFER_BIT);webgl.drawArrays(webgl.POINTS, 0, 1);}</script>
</head><body onload="init()"><canvas id='myCanvas' width="1024" height='768'></canvas>
</body></html>
效果如下: