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
| "use strict";
var canvas; var gl;
var theta = 0.0; var thetaLoc; var direction = 1; var speed = 50; var sides = 4;
function changeDir() { direction *= -1; }
function initRotSquare() { canvas = document.getElementById("rot-canvas"); gl = canvas.getContext("webgl2"); if (!gl) { alert("WebGL isn't available"); }
gl.viewport(0, 0, canvas.width, canvas.height); gl.clearColor(1.0, 1.0, 1.0, 1.0);
var program = initShaders(gl, "rot-v-shader", "rot-f-shader"); gl.useProgram(program);
updateVertices(sides);
thetaLoc = gl.getUniformLocation(program, "theta");
document.getElementById("speedcon").oninput = function(event) { speed = 100 - event.target.value; updateSpeedDisplay(event.target.value); }
document.getElementById("sidesRange").oninput = function(event) { sides = event.target.value; updatePolygonSidesDisplay(sides); updateVertices(sides); }
renderSquare(); }
function updateVertices(numSides) { var vertices = []; var angleStep = (2 * Math.PI) / numSides;
for (var i = 0; i < numSides; i++) { var angle = i * angleStep; vertices.push(Math.cos(angle), Math.sin(angle), 0); }
vertices = new Float32Array(vertices);
var bufferId = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, bufferId); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var vPosition = gl.getAttribLocation(gl.getParameter(gl.CURRENT_PROGRAM), "vPosition"); gl.vertexAttribPointer(vPosition, 3, gl.FLOAT, false, 0, 0); gl.enableVertexAttribArray(vPosition); }
function renderSquare() { gl.clear(gl.COLOR_BUFFER_BIT); theta += direction * 0.1; gl.uniform1f(thetaLoc, theta); gl.drawArrays(gl.TRIANGLE_FAN, 0, sides); setTimeout(function() { requestAnimFrame(renderSquare); }, speed); }
function updateSpeedDisplay(value) { document.getElementById("speedValue").textContent = value; }
function updatePolygonSidesDisplay(value) { document.getElementById("sidesValue").textContent = value; }
|