Guest User

Untitled

a guest
Mar 18th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>WebGL</title>
  5. <style>html, body { margin: 0; padding: 0; height: 100%; background-color: #293039; display: flex; justify-content: center; align-items: center; }</style>
  6. </head>
  7. <body>
  8. <canvas id="canvas" width="640" height="480"></canvas>
  9. <script>
  10. const canvas = document.getElementById('canvas');
  11. const gl = canvas.getContext('webgl');
  12.  
  13. // Create and compile a vertex shader.
  14. const vertexShader = gl.createShader(gl.VERTEX_SHADER);
  15. gl.shaderSource(vertexShader, `
  16. attribute vec2 position;
  17.  
  18. void main() {
  19. gl_Position = vec4(position, 0.0, 1.0);
  20. }
  21. `);
  22. gl.compileShader(vertexShader);
  23.  
  24. // Create and compile a fragment shader.
  25. const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  26. gl.shaderSource(fragmentShader, `
  27. void main(void) {
  28. gl_FragColor = vec4(0, 0.77, 0.8, 1.0);
  29. }
  30. `);
  31. gl.compileShader(fragmentShader);
  32.  
  33. // Compile, link and enable the shader program.
  34. const program = gl.createProgram();
  35. gl.attachShader(program, vertexShader);
  36. gl.attachShader(program, fragmentShader);
  37. gl.linkProgram(program);
  38. gl.useProgram(program);
  39.  
  40. // Defines a 2D quad in clip-space using two triangles in counter-clockwise winding order.
  41. // (-1, +1) TL ┌─────┐ TR (+1, +1)
  42. // │ ╲ │
  43. // │ ╲ │
  44. // (-1, -1) BL └─────┘ BR (+1, -1)
  45. const dimensions = 2;
  46. const vertices = new Float32Array([
  47. // Top right triangle.
  48. -1, +1, // TL
  49. +1, -1, // BR
  50. +1, +1, // TR
  51. // Bottom left triangle.
  52. -1, +1, // TL
  53. -1, -1, // BL
  54. +1, -1, // BR
  55. ]);
  56. // Create a buffer on the GPU, bind to it and upload the data.
  57. const positionBuffer = gl.createBuffer();
  58. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  59. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  60.  
  61. // Get a reference to the position attribute, enable it, and point the attribute to the uploaded position buffer.
  62. const positionAttribute = gl.getAttribLocation(program, 'position');
  63. gl.enableVertexAttribArray(positionAttribute);
  64. gl.vertexAttribPointer(positionAttribute, dimensions, gl.FLOAT, false, 0, 0);
  65.  
  66. // Render to the canvas.
  67. gl.drawArrays(gl.TRIANGLES, 0, vertices.length / dimensions);
  68. </script>
  69. </html>
Add Comment
Please, Sign In to add comment