Rotation

We can rotate an object by dragging the mouse, recording the coordinates, and calculating the distances covered.


RESETRUNFULL
<!DOCTYPE html><html><head>
<script src="/shared/webgl-library.js"></script>
<script id="vs" type="x-shader/x-vertex">
   attribute vec4 p;
   uniform mat4 u_modelMatrix;
   void main(){
      gl_Position = u_modelMatrix * p;
   }
</script>
<script id="fs" type="x-shader/x-fragment">
   precision mediump float;
   void main(){
      gl_FragColor=vec4(1.0,1.0,1.0,1.0);
   }
</script>
<script>
function initEventHandlers(canvas, currentAngle) {
  var dragging = false;
  var lastX = -1, lastY = -1;
  canvas.onmousedown = function(ev) {
    var x = ev.clientX, y = ev.clientY;
    var rect = ev.target.getBoundingClientRect();
    if (rect.left <= x && x < rect.right &&
         rect.top <= y && y < rect.bottom) {
      lastX = x; lastY = y;
      dragging = true;
    }
  };
  canvas.onmouseup = function(ev) { dragging = false;};
  canvas.onmousemove = function(ev) {
    var x = ev.clientX, y = ev.clientY;
    if (dragging) {
      var factor = 100/canvas.height;
      var dx = factor * (x - lastX);
      var dy = factor * (y - lastY);
      currentAngle[0] = Math.max(Math.min(currentAngle[0] + dy, 90.0), -90.0);
      currentAngle[1] = currentAngle[1] + dx;
    }
    lastX = x, lastY = y;
  };
}
function WebGLStart(){
   var canvas = document.getElementById("myCanvas");
   var gl = canvas.getContext("webgl");
   initShaders(gl,"vs","fs");
   var vertices = new Float32Array([0.0,-0.5,0.0,  -0.5,0.5,0.0,  0.5,0.5,0.0]);
   initArrayBuffer(gl, 'p', vertices, 3);
   gl.clearColor(0.0, 0.0, 0.0, 1.0);
   var u_modelMatrix = gl.getUniformLocation(gl.program, 'u_modelMatrix');
   var modelMatrix = new Matrix4();
   var currentAngle = [0.0, 0.0]; // ([x-axis, y-axis] degrees)
   initEventHandlers(canvas, currentAngle);
   var tick = function() {
      modelMatrix.setIdentity();
      modelMatrix.rotate(currentAngle[0], 1.0, 0.0,0.0); //x-axis
      modelMatrix.rotate(currentAngle[1], 0.0, 1.0,0.0); //y-axis
      gl.uniformMatrix4fv(u_modelMatrix,false, modelMatrix.entries);
      gl.clear(gl.COLOR_BUFFER_BIT);
      gl.drawArrays(gl.TRIANGLES,0,3);
      requestAnimationFrame(tick, canvas);
   };
   tick();
}
</script></head>
<body onload="WebGLStart()">
   <canvas id="myCanvas" width="500" height="500"></canvas>
</body></html>