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
| "use strict";
function main() { var canvas = document.querySelector("#canvas"); var gl = canvas.getContext("webgl"); if (!gl) { return; }
var program = webglUtils.createProgramFromScripts(gl, ["vertex-shader-2d", "fragment-shader-2d"]); gl.useProgram(program);
var positionLocation = gl.getAttribLocation(program, "a_position");
var resolutionLocation = gl.getUniformLocation(program, "u_resolution"); var colorLocation = gl.getUniformLocation(program, "u_color"); var translationLocation = gl.getUniformLocation(program, "u_translation");
var positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); setGeometry(gl);
var translation = [0, 0]; var color = [Math.random(), Math.random(), Math.random(), 1];
drawScene();
webglLessonsUI.setupSlider("#x", {slide: updatePosition(0), max: gl.canvas.width }); webglLessonsUI.setupSlider("#y", {slide: updatePosition(1), max: gl.canvas.height});
function updatePosition(index) { return function(event, ui) { translation[index] = ui.value; drawScene(); }; }
function drawScene() { webglUtils.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.enableVertexAttribArray(positionLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
var size = 2; var type = gl.FLOAT; var normalize = false; var stride = 0; var offset = 0; gl.vertexAttribPointer( positionLocation, size, type, normalize, stride, offset);
gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);
gl.uniform4fv(colorLocation, color);
gl.uniform2fv(translationLocation, translation);
var primitiveType = gl.TRIANGLES; var offset = 0; var count = 18; gl.drawArrays(primitiveType, offset, count); } }
function setGeometry(gl) { gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([ 0, 0, 30, 0, 0, 150, 0, 150, 30, 0, 30, 150,
30, 0, 100, 0, 30, 30, 30, 30, 100, 0, 100, 30,
30, 60, 67, 60, 30, 90, 30, 90, 67, 60, 67, 90, ]), gl.STATIC_DRAW); }
main();
|