Implement a Mouse Trackball in Javascript
This code snippit is a set of mouse handlers that lets you rotate scenes in WebGL
- The handleMosueDown function detects when a mouse button is held down and enables mouse tracking.
- The handleMouseMove function calculates x and y movement and rotates the transformation Matrix.
- The handleMouseUp function stops the rotation by turning off the mouseDown variable.
//mouse_util.js
// helper skeleton controls for mouse movements.
function degToRad(degrees) {
return degrees * Math.PI / 180;
}
// variable that is true if the mouse button is pressed down
var mouseDown = false;
var lastMouseX = null;
var lastMouseY = null;
var objRotationMatrix = mat4.create();
mat4.identity(objRotationMatrix);
function handleMouseDown(event) {
mouseDown = true;
lastMouseX = event.clientX;
lastMouseY = event.clientY;
}
function handleMouseUp(event) {
mouseDown = false;
}
// based on mouse movement calculate rotation values.
function handleMouseMove(event) {
if (!mouseDown) {
return;
}
var newX = event.clientX;
var newY = event.clientY;
var deltaX = newX - lastMouseX;
var newRotationMatrix = mat4.create();
mat4.identity(newRotationMatrix);
// rotate around Y axis
mat4.rotate(newRotationMatrix, degToRad(deltaX / 10), [0, 1, 0]);
var deltaY = newY - lastMouseY;
// rotate around the X axis
mat4.rotate(newRotationMatrix, degToRad(deltaY / 10), [1, 0, 0]);
mat4.multiply(newRotationMatrix, objRotationMatrix, objRotationMatrix);
// objRotrationMatrix is used in drawScene to rotate the view.
// this is the 'output' of this method.
// if you use it in draw scene to rotate the first transformation in the pipeline
// everything will work for you.
lastMouseX = newX
lastMouseY = newY;
}
The following code snipit connects the mouse functions as handlers for the canvas code:
You could use it where you set up your webgl context
//Initialize everything for starting up a simple webGL application
function startHelloWebGL()
{
// first initialize webgl components
var gl = initGLScene();
// initialize the pipeline by enabling shaders
initShaders();
// initialize the elements of the scene that are needed
initGeometry(); // create geometry
initTextures(); // load and attach textures
gl.clearColor(0.4,0.4,0.4,1.0);
gl.enable(gl.DEPTH_TEST);
// attach 'Handler' functions to handle events generated by the canvas.
// set mouse handlers for controlling rotation
// get a handle from the DOM to connect the mouse handlers
var acanvas = document.getElementById("hellowebgl");
acanvas.onmousedown = handleMouseDown; // handle mouse down events
// we attached to the document instead of just canvas for when mouse is not over canvas
document.onmouseup = handleMouseUp; // handle when mouse is relealsed
document.onmousemove = handleMouseMove; // handle mouse movement
..... your code here ...
}