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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| <!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> * { margin: 0; padding: 0; }
#canvas { width: 99vw; height: 99vh; } </style> </head> <body> <canvas id="canvas"></canvas>
<script id="vertex-shader-2d" type="notjs">
attribute vec4 a_position;
void main() { gl_Position = a_position; } </script>
<script id="fragment-shader-2d" type="notjs"> precision mediump float;
void main() { gl_FragColor = vec4(1, 0, 0.5, 1); } </script>
<script> const canvas = document.querySelector("#canvas"); const gl = canvas.getContext("webgl");
const vertexShaderSource = document.querySelector("#vertex-shader-2d").text; const fragmentShaderSource = document.querySelector( "#fragment-shader-2d" ).text;
const vertexShader = createShader( gl, gl.VERTEX_SHADER, vertexShaderSource );
const fragmentShader = createShader( gl, gl.FRAGMENT_SHADER, fragmentShaderSource );
function createShader(gl, type, source) { const shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (success) { return shader; } console.log(gl.getShaderInfoLog(shader)); gl.deleteShader(shader); }
function createProgram(gl, vertexShader, fragmentShader) { const program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program);
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (success) return program;
console.log(gl.getProgramInfoLog(program)); gl.deleteProgram(program); }
const program = createProgram(gl, vertexShader, fragmentShader);
const positionAttributeLocation = gl.getAttribLocation( program, "a_position" );
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [0, 0, 0, 0.5, 0.7, 0];
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW );
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.enableVertexAttribArray(positionAttributeLocation);
const size = 2; const type = gl.FLOAT; const normalize = false; const stride = 0; const offset = 0;
gl.vertexAttribPointer( positionAttributeLocation, size, type, normalize, stride, offset );
const primitiveType = gl.TRIANGLES; const count = 3; gl.drawArrays(primitiveType, offset, count); </script> </body> </html>
|