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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
| <body> <canvas id="canvas"></canvas> <script type="shader-source" id="vertexShader"> precision mediump float; attribute vec2 a_Position; attribute vec2 a_Screen_Size; attribute vec4 a_Color; varying vec4 v_Color;
void main(){ vec2 position = (a_Position / a_Screen_Size) * 2.0 - 1.0; position = position * vec2(1.0, -1.0); gl_Position = vec4(position, 0.0, 1.0); v_Color = a_Color;
} </script> <script type="shader-source" id="fragmentShader"> precision mediump float; varying vec4 v_Color;
void main(){ vec4 color = v_Color / vec4(255, 255, 255, 1); gl_FragColor = color; } </script> <script src="../utils/webgl-helper.js"></script> <script> let canvas = getCanvas('#canvas'); resizeCanvas(canvas); let gl = getContext(canvas); let program = createSimpleProgramFromScript(gl, 'vertexShader', 'fragmentShader');
gl.useProgram(program);
let color = randomColor(); let u_Color = gl.getUniformLocation(program, 'u_Color'); gl.uniform4f(u_Color, color.r, color.g, color.b, color.a); let a_Screen_Size = gl.getAttribLocation(program, 'a_Screen_Size'); gl.vertexAttrib2f(a_Screen_Size, canvas.width, canvas.height);
let positions = [ 30, 30, 255, 0, 0, 1, 30, 300, 0, 255, 0, 1, 300, 300, 0, 255, 0, 1, 30, 30, 255, 255, 0, 1, 300, 300, 255, 255, 0, 1, 300, 30, 0, 0, 255, 1 ];
let a_Position = gl.getAttribLocation(program, 'a_Position'); let a_Color = gl.getAttribLocation(program, 'a_Color');
gl.enableVertexAttribArray(a_Position); gl.enableVertexAttribArray(a_Color); let buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 24, 0); gl.vertexAttribPointer(a_Color, 4, gl.FLOAT, false, 24, 8); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); gl.clearColor(0, 0, 0, 1);
function render(gl) { gl.clear(gl.COLOR_BUFFER_BIT); if (positions.length > 0) { gl.drawArrays(gl.TRIANGLES, 0, positions.length / 6); } } render(gl); </script> </body>
|