Rotating CSS cube on fixed axes
Note: It turns out this problem is kinda difficult to solve in CSS. If you really need a complex transformation like this where new transformations should be applied onto the previous state maybe try some other method.
Anyway, I'm first going to explain the steps I went through, the problems I faced and the steps I took to solve it. It's really convoluted and messy but it works. At the end, I've put the code I used as JavaScript.
Explanation
So I've come to understand a couple of things about transformations in CSS. One main thing is that when you pass a string of transformations to the transform
property, like this
transform: "rotateX(90deg) rotateY(90deg)"
these transformations are not combined into one single composite transformation. Instead the first one is applied, then the next one is applied on top of that and so on. So while I expected the cube to rotate diagonally by 90degrees, it didn't do that.
As @ihazkode suggested, rotate3d
was the way to go. It allows rotation around any arbitrary axes instead of being limited to X, Y and Z axes. rotate3d
takes 3 arguments
rotate3d(x, y, z, angle).
x y and z specify the rotation axis. The way to look at it is like this: Imagine drawing a line from (x,y,z)
to the transform-origin
you specified. This line will the be axis of rotation. Now imagine you are looking towards the origin from (x,y,z)
. From this view, the object will rotate clockwise by angle
degrees.
However, I still faced a problem. Although rotate3d
let's me rotate the cube in a far more intuitive way, I still faced the problem where after rotating the cube once (with the mouse) if I again clicked and tried rotating the cube, it would snap back to its original state and rotate from there, which is not what I wanted. I wanted it to rotate from it's current state, whatever rotation state that may be.
I found a very messy way to do it using the matrix3d
property. Basically I'd follow these steps every time the mousedown and mousemove events occurred
I'd calculate a vector based on the position that mousedown occured and the current mouse position from mousemove. For example, if mousedown occured at (123,145) and then a mousemove occured at (120,143), then a vector can be made from these two points as [x, y, z, m] where
x is the x component which is the new x position minus the mouse down x position = 120 - 123 = -3
y is the y component, similar to x, which = 143-145 = -2
z = 0 since the mouse cannot move in the z direction
m is the magnitude of the vector which can be calculated as squareroot(x2 + y2) = 3.606
So the mouse movement can be represented as the vector [-3, -2, 0, 3.606]
Now notice that the rotation vector of the cube should be perpendicular to the mouse movement. For example, if I move my mouse straight up by 3 pixels, the mouse movement vector is [0,-1,0,3] (y is negative because in the browser the top left corner is the origin). But if I use this vector as the rotation vector and pass it into
rotate3d
, that rotates the cube clockwise (when looking from above) around the y axis. But that's not right! If I swipe my mouse upwards, it should rotate around it's x axis! To solve this, just swap x and y and negate the new x. That is, the vector should be [1,0,0,3]. Therefore, the vector from step 1 should instead be [2,-3,0,3.606].
Now I just set the transform
property of my cube as
transform: "rotate3d(2,-3,0,3.606)"
So now, I figured out how to rotate the cube correctly based on mouse movement, without facing the previous problem of trying to make a rotateX
and then rotateY
.
- Now the cube can rotate correctly. But what if I let go of the mouse and then again perform a mousedown and try rotating the cube. If I follow the same steps from above, what happens is the new vector that I pass to
rotate3d
will replace the old one. So the cube is reset to it's initial position and the new rotation is applied to it. But that's not right. I want the cube to remain in the state it was in previously, and then from that state it should rotate further by the new rotation vector.
To do this, I need to append the new rotation onto the previous rotation. So I could do something like this
transform: "rotate3d(previous_rotation_vector) rotate3d(new_rotation_vector)"
After all, this would perform the first rotation and then perform the second rotation on top of that. But then imagine performing 100 rotations. The transform
property would need to be fed 100 rotate3d
s. That wouldn't be the best way to go about this.
Here's what I figured. At any point if you query the transform
css property of a node like
$('.cube').css('transform');
you get back one of 3 values: "none" if the object hasn't been transformed at all so far, a 2D transformation matrix (looks like matrix2d(...)
) if only 2D transformations have peen performed, or a 3D transformation matrix (looks like matrix3d(...)
otherwise.
So what I can do is, immediately after performing a rotate operation, query and get the transformation matrix of the cube and save it. Next time I perform a new rotation, do this:
transform: "matrix3d(saved_matrix_from_last_rotation) rotate3d(new_rotation_vector)"
This would first transform the cube to it's last state of rotation and then apply the new rotation on top of that. No need to pass a 100 rotate3d
s.
- There's one last problem I discovered. There's still the same issue of the axes of an object rotating along with the object.
Suppose I rotate the cube 90 degrees along the x axis with
transform: rotate3d(1,0,0,90deg);
and then rotate it from there around it's the y axis by 45 degrees with
transform: matrix3d(saved values) rotate3d(0,1,0,45deg)
I would expect the cube to rotate upwards 90 and then rotate to the right by 45. But instead it rotated up by 90 and then rotated around currently visible front face by 45 instead of rotating to the right. It's the exact same problem I mentioned in my question. The problem is, although rotate3d
allows you to rotate an object around any arbitrary axis of rotation, that arbitrary axis is still with reference to the axis of the object and not by a fixed x, y and z axes with respect to the user. It's the same gosh darn problem of the axes rotating with the object.
So if the cube is currently in some rotated state and I want it to rotate further on a vector (x,y,z) obtained through the mouse as in step 1 and 2, I first need to somehow transform this vector into it's correct position based on what state the cube is in currently.
What I noticed is if you take the rotation vector as a 4x1 matrix like this
x
y
z
angle
and took the matrix3d
matrix as a 4x4 matrix, then if I multiplied the 3D transformation matrix by the rotation vector, I get the old rotation vector but transformed into it's correct position. Now I can apply this vector after the 3d matrix as in step 3 and FINALLY the cube is behaving exactly the way it should.
JavaScript code
Okay that was enough talk. Here's the code I used. Sorry if it's not very clear.
var lastX; //stores x position from mousedown
var lastY; //y position from mousedown
var matrix3d = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] //this identity matrix performs no transformation
$(document).ready(function() {
$('body').on('mousedown', function(event) {
$('body').on('mouseup', function() {
$('body').off('mousemove');
m = $('.cube').css('transform');
//if this condition is true, transform property is either "none" in initial state or "matrix2d" which happens when the cube is at 0 rotation.
if(m.match(/matrix3d/) == null)
matrix3d = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]; //identity matrix for no transformaion
else
matrix3d = stringToMatrix(m.substring(8,m.length));
});
lastX=event.pageX;
lastY=event.pageY;
$('body').on('mousemove', function (event) {
var x = -(event.pageY - lastY);
var y = event.pageX - lastX;
var angle = Math.sqrt(x*x + y*y);
var r = [[x],[y],[0],[angle]]; //rotation vector
rotate3d = multiply(matrix3d, r); //multiply to get correctly transformed rotation vector
var str = 'matrix3d' + matrixToString(matrix3d)
+ ' rotate3d(' + rotate3d[0][0] + ', ' + rotate3d[1][0] + ', ' + rotate3d[2][0] + ', ' + rotate3d[3][0] + 'deg)';
$('.cube').css('transform',str);
});
});
});
//converts transform matrix to a string of all elements separated by commas and enclosed in parentheses.
function matrixToString(matrix) {
var s = "(";
for(i=0; i<matrix.length; i++) {
for(j=0; j<matrix[i].length; j++) {
s+=matrix[i][j];
if(i<matrix.length-1 || j<matrix[i].length-1) s+=", ";
}
}
return s+")";
}
//converts a string of transform matrix into a matrix
function stringToMatrix(s) {
array=s.substring(1,s.length-1).split(", ");
return [array.slice(0,4), array.slice(4,8), array.slice(8,12), array.slice(12,16)];
}
//matrix multiplication
function multiply(a, b) {
var aNumRows = a.length, aNumCols = a[0].length,
bNumRows = b.length, bNumCols = b[0].length,
m = new Array(aNumRows); // initialize array of rows
for (var r = 0; r < aNumRows; ++r) {
m[r] = new Array(bNumCols); // initialize the current row
for (var c = 0; c < bNumCols; ++c) {
m[r][c] = 0; // initialize the current cell
for (var i = 0; i < aNumCols; ++i) {
m[r][c] += a[r][i] * b[i][c];
}
}
}
return m;
}
Controlling CSS cube rotation(transform) and extracting values from 3d matrix
The problem with the attempt 2 is that rotateAxisAngle does the matrix multiplication in the oposite order of what you want. And, worse still, there is no function in the class to do the multiplication in the order that you want.
As an alternate way, I have choose to use the browser itself to do the math.
I create a div that will be hidden, and where I will apply the transforms to get the new matrix.
With this approach, the javascript gets even shorter:
function applyTransform (transform) {
var cubeCalculator = $('.cubecalculator');
var cube = $('#cube');
var matrix = cubeCalculator.css('webkitTransform');
var composite = transform + ' ' + matrix;
cubeCalculator.get(0).style.webkitTransform = composite;
matrix = cubeCalculator.css('webkitTransform');
cube.get(0).style.webkitTransform = matrix;
}
// rotate using arrow keys
$(document).keyup(function(e) {
e.preventDefault();
var key = e.which,
arrow = {left: 37, up: 38, right: 39, down: 40},
t;
switch(key) {
case arrow.left:
t = 'rotateY(-90deg)';
break;
case arrow.right:
t = 'rotateY(90deg)';
break;
case arrow.up:
t = 'rotateX(90deg)';
break;
case arrow.down:
t = 'rotateX(-90deg)';
break;
}
applyTransform (t);
});
I think that the code is quite self explanatory: I apply the transform to the element as a composite of the new transform and the current transform (you don't need to extract the values from the matrix, can be applied as is)
demo
(I don't know why, it didn't work in codepen. have moved it to fiddle ...)
Finally I got the * Firefox to behave !
function applyTransform (transform1, transform2) {
var matrix, composite1, composite2;
var cubeCalculator = $('.cubecalculator');
var cube = $('#cube');
matrix = cubeCalculator.css('transform');
composite1 = transform1 + ' ' + matrix;
composite2 = transform2 + ' ' + matrix;
cubeCalculator.get(0).style.transform = composite2;
cube.get(0).style.transition = 'none';
cube.get(0).style.transform = composite1;
window.setTimeout (function() {
cube.get(0).style.transform = composite2;
cube.get(0).style.transition = 'transform 1s';
}, 10 );
}
// rotate using arrow keys
$(document).keyup(function(e) {
e.preventDefault();
var key = e.which,
arrow = {left: 37, up: 38, right: 39, down: 40},
t1, t2;
switch(key) {
case arrow.left:
t1 = 'rotateY(0deg)';
t2 = 'rotateY(-90deg)';
break;
case arrow.right:
t1 = 'rotateY(0deg)';
t2 = 'rotateY(90deg)';
break;
case arrow.up:
t1 = 'rotateX(0deg)';
t2 = 'rotateX(90deg)';
break;
case arrow.down:
t1 = 'rotateX(0deg)';
t2 = 'rotateX(-90deg)';
break;
}
applyTransform (t1, t2);
});
A little bit more complex code, but makes to the browser perfectly clear what you want it to do ...
Works fine as long as you wait till the transition is over.
3D Rotation warps cube
You need temporary variables x, y like:
x = v.x * cosZ - v.y * sinZ;
y = v.y * cosZ + v.x * sinZ;
v.x = x;
v.y = y;
Otherwise the computation of v.y is using the wrong v.x
3D CSS Cube - Strange Rotation Inconsistency (Solved: Gimbal Lock)
This is a normal problem with 3D rotation using 3 axes called Gimbal_lock
Gimbal lock is the loss of one degree of freedom in a three-dimensional, three-gimbal mechanism that occurs when the axes of two of the three gimbals are driven into a parallel configuration, "locking" the system into rotation in a degenerate two-dimensional space.
Solutions are usually either using matrices or quaternions for rotation or staying with 3 axes but decomposing them and recompositing to avoid these issues.
const rotation_degree = { 'X': 0, 'Y': 0, 'Z': 0 };const axisIdToAxis = { 'X': [1, 0, 0], 'Y': [0, 1, 0], 'Z': [0, 0, 1] };const currentMatrix = new DOMMatrix;
$(document).on ("click", "button", function (e){ const degree = parseInt ($(this).attr ("data-degree")); const axis = $(this).attr ("data-axis"); // Animate on an unused property $(".cube").css ("text-indent", rotation_degree[axis]); $('.cube').animate ( { textIndent: rotation_degree[axis] + degree }, { step: function (now,fx) { rotation_degree[axis] = now;
// Center cube in scene const transform = `translateZ(-50px) rotate${axis}(${now}deg) ${currentMatrix}`; $(this).css ('transform', transform); }, complete: function() { // apply rotation to currentMatrix currentMatrix.preMultiplySelf( new DOMMatrix().rotateAxisAngleSelf( ...axisIdToAxis[axis], degree)); // zero this out since we applied it above rotation_degree[axis] = 0; },
duration: 'slow', queue: true,
}, 'linear', ); });
html, body { width: 100%; height: 100%;}
.scene { width: 100px; height: 100px; perspective: 100px; background-color: rgb(0,0,0);}
.cube { width:100%; height:100%; position:relative; transform-style:preserve-3d; transform: translateZ(-50px); text-indent: 0; }
.face { width: 100%; height: 100%; position: absolute; background-color: rgba(3, 121, 255, 0.5); color: #FFF; line-height: 100px; text-indent: 0; text-align: center;}
.front { transform: rotateY(0deg) translateZ(50px); }.right { transform: rotateY(90deg) translateZ(50px); }.left { transform: rotateY(-90deg) translateZ(50px); }.back { transform: rotateY(180deg) translateZ(50px); }.top { transform: rotateX(90deg) translateZ(50px); }.bottom { transform: rotateX(-90deg) translateZ(50px); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="scene">
<div class="cube"> <div class="face front">front</div> <div class="face right">right</div> <div class="face left">left</div> <div class="face back">back</div> <div class="face top">top</div> <div class="face bottom">bottom</div> </div> </div>
<button data-degree="45" data-axis="X"> X-Axis (+)</button>
<button data-degree="-45" data-axis="X"> X-Axis (-)</button>
<button data-degree="45" data-axis="Y"> Y-Axis (+)</button>
<button data-degree="-45" data-axis="Y"> Y-Axis (-)</button>
<button data-degree="45" data-axis="Z"> Z-Axis (+)</button>
<button data-degree="-45" data-axis="Z"> Z-Axis (-)</button>
Related Topics
How to Extend a Class from a CSS File in SASS
Svg <Mask> Tag Required for Firefox But Appears to Break CSS Mask in Chrome
How to Custom Table Responsive Materialize
Excluding an Element from Nth-Child Pattern
Apply Blur Effect to Parent Container Only
Why Position Sticky Is Not Working If Followed by Position Absolute Element
Add Space Between HTML Elements Only Using CSS
How to Get Perfect Border Radius on Images in All Browsers
Animate Text Fill from Left to Right
Cannot Change the Content of Visited :Before Pseudo-Elements
How to Change the Font Size of the List (Not the Initial View)
How to Center One of the Flex/Grid Children(More Than Three) and with Different Widths