<!DOCTYPE html> <html> <head> <title>WebGL</title> <meta charset="UTF-8"> <script…
- User
window.onload = () => { const aMyWebGL = new MyWebGL(); // Retrieve element const aCanvas = document.getElementById("id_Canvas"); // Get the rendering context for WebGL const gl = aMyWebGL.initGL(aCanvas, true); if (!gl) { console.error("Failed to get the rendering context for WebGL"); return; } const aProgram = aMyWebGL.initShadersAndMakeCurrent(astrVertexShader, astrFragmentShader); if (!aProgram) { console.error("!aProgram"); return; } const a_Position = gl.getAttribLocation(aProgram, "a_Position"); if (0 > a_Position) { console.error("Failed to get the storage location of a_Position"); return; } const a_PointSize = gl.getAttribLocation(aProgram, "a_PointSize"); if (0 > a_PointSize) { console.error("Failed to get the storage location of a_PointSize"); return; }
// Get the storage location of u_FragColorconst u_FragColor = gl.getUniformLocation(aProgram, "u_FragColor"); if (!u_FragColor) { console.error("Failed to get the storage location of u_FragColor"); return; }
// Pass vertex position to attribute variable gl.vertexAttrib3f(a_Position, 0.5, 0.0, 0.0); gl.vertexAttrib1f(a_PointSize, 15.0);
// Pass the color of a point to u_FragColor variable gl.uniform4f(u_FragColor, 0.0, 1.0, 0.0, 1.0);
// Set clear color gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT);
// Draw a point gl.drawArrays(gl.POINTS, 0, 1); }
class MyWebGL { gl; VShader; FShader; Program;
static createGL(aCanvas, avAttribs) { if (!aCanvas) { console.error("createGL : ! aCanvas", aCanvas); return null; } const avstrNames = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; let gl = null, n = avstrNames.length; for (let i = 0; i < n; ++i) { try { gl = aCanvas.getContext(avstrNames[i], avAttribs); } catch (e) { if (gl) { break; } } } return gl; }}
export default { createProgram(gl) { if (!gl) { console.error('createProgramObject: gl is undefined'); return null; } const vs = this.createShader(gl); const fs = this.createShader(gl);
if (!vs || !fs) { return null; } const program = gl.createProgram(); // Create a program object if (!program) { console.error('createProgramObject: Shader undefined'); return null; } gl.attachShader(program, vs); // Attach the vertex shader gl.attachShader(program, fs); // Attach the fragment shader gl.linkProgram(program); // Link the program object if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { // Check the result of linking console.error('Failed to link program: ' + gl.getProgramInfoLog(program)); return null; } return program; },};
// Retrieve element const canvas = document.getElementById('webgl');
// Get the rendering context for WebGL const gl = getWebGLContext(canvas); if (!gl) { console.error('Failed to get the rendering context for WebGL'); return; }
- Assistant