WebGL is a software library and cross-platform API that extends the capability of the JavaScript programming language.
That brings OpenGL to the web as a 3D drawing context within HTML
Today we present a simple example of using WebGL.
Here, there is an HTML content, javascript, and content of WebGL content.
The three main sections are combined.
In section WebGL enter and the fragment shader and vertex shader.
For those who have worked with OpenGL will be easy to recognize specific functions.
The full example can be found at jsfiddle.net
Also, the source code is written for OpenGL format file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function shaderProgram(gl, vs, fs) { var prog = gl.createProgram(); var addshader = function(type, source) { var s = gl.createShader((type == 'vertex') ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); gl.shaderSource(s, source); gl.compileShader(s); if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { throw "Could not compile "+type+ " shader:\n\n"+gl.getShaderInfoLog(s); } gl.attachShader(prog, s); }; addshader('vertex', vs); addshader('fragment', fs); gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { throw "Could not link the shader program!"; } return prog; } function attributeSetFloats(gl, prog, attr_name, rsize, arr) { gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(arr), gl.STATIC_DRAW); var attr = gl.getAttribLocation(prog, attr_name); gl.enableVertexAttribArray(attr); gl.vertexAttribPointer(attr, rsize, gl.FLOAT, false, 0, 0); } function draw() { try { var gl = document.getElementById("webgl").getContext("experimental-webgl"); if (!gl) { throw "x"; } } catch (err) { throw "Your web browser does not support WebGL!"; } gl.clearColor(0.0, 1.0, 0.0, 1); gl.clear(gl.COLOR_BUFFER_BIT); var prog = shaderProgram(gl, "attribute vec3 pos;"+ "void main() {"+ " gl_Position = vec4(pos, 2.0);"+ "}", "void main() {"+ " gl_FragColor = vec4(0.0, 0.5, 0.1, 1.0);"+ "}" ); gl.useProgram(prog); attributeSetFloats(gl, prog, "pos", 3, [ -1, 1, 0, 0, 1, 0, 0, -1, 0, 1, 0, 0 ]); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); } function init() { try { draw(); } catch (e) { alert("Error: "+e); } } setTimeout(init, 100); |