Rotating CSS cube on fixed axes
I have a cube constructed using CSS. It's made of 6 faces and each face is transformed to form one face of the cube, and all the 6 faces are under one <div>
with the class .cube
. Any rotation I do to the cube is done on this enclosing cube
class.
I want the cube to rotate based on mouse drag input. So far it kinda works. I just translate x and y mouse movement into cube rotation about the x and y axes.
But there's one major problem with this. I perform the rotation as a simple
transform: rotateX(xdeg) rotateY(ydeg)
CSS property. The issue with this is that the y axis of rotation is getting rotated with the x rotation.
Suppose I rotate the cube 90 degrees around the x axis. Now, if I try to rotate the cube 90 degrees along the y axis as well, I would expect the cube to rotate 90 degrees to the right or left (from my perspective). But instead, it's rotating about it's currently visible front face. That is, the y axis got rotated 90 degrees thanks to the x axis rotation that came first, and so now from the perspective of the user, it looks as if the cube is rotating around it's z axis.
I want to be able to rotate the cube in a way that the xy and z axes remain fixed from the perspective of the user. Also the cube needs to rotate from the current state in case the user lifts their finger off the button and clicks again and drags.
I've been finding this difficult to do. I feel this may not be possible using just the rotateX/Y/Z
properties and instead I might have to use the 3d matrix or rotate3d properties?
I know this may not be the easiest thing to achieve using CSS but I still want to do it. Could someone point me in the right direction on how to solve this problem?
#cube-wrapper {
position: absolute;
left: 50%;
top: 50%;
perspective: 1500px;
}
.cube {
position: relative;
transform-style: preserve-3d;
}
/* Size and border color for each face */
.face {
position: absolute;
width: 200px;
height: 200px;
border: solid green 3px;
}
/* Transforming every face into their correct positions */
#front_face {
transform: translateX(-100px) translateY(-100px) translateZ(100px);
}
#back_face {
transform: translateX(-100px) translateY(-100px) translateZ(-100px);
}
#right_face {
transform: translateY(-100px) rotateY(90deg);
}
#left_face {
transform: translateY(-100px) translateX(-200px) rotateY(90deg);
}
#top_face {
transform: translateX(-100px) translateY(-200px) rotateX(90deg);
}
#bottom_face {
transform: translateX(-100px) rotateX(90deg);
}
.cube {
transform: rotateX(90deg) rotateY(90deg);
}
<!-- Wrapper for the cube -->
<div id="cube-wrapper">
<div class="cube">
<!-- A div for each face of the cube -->
<div id="front_face" class="face"></div>
<div id="right_face" class="face"></div>
<div id="back_face" class="face"></div>
<div id="left_face" class="face"></div>
<div id="top_face" class="face"></div>
<div id="bottom_face" class="face"></div>
</div>
</div>
use rotate3d
It's relatively easy to use, but you would still need to link up your current tracking script to the right parameters
You can control the rotation amount (in terms of degrees) and which axis is affected (x,y,z). You can select one more at the same time.
Example 1 - rotate X axis:
#cube-wrapper {
position: absolute;
left: 50%;
top: 50%;
perspective: 1500px;
}
.cube {
position: relative;
transform-style: preserve-3d;
animation-name: rotate;
animation-duration: 30s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@keyframes rotate {
0% {
transform: rotate3d(0, 0, 0, 0);
}
100% {
transform: rotate3d(1, 0, 0, 360deg); /*controls rotation amount on one axis) */
;
}
}
/* Size and border color for each face */
.face {
position: absolute;
width: 200px;
height: 200px;
border: solid green 3px;
}
/* Transforming every face into their correct positions */
#front_face {
transform: translateX(-100px) translateY(-100px) translateZ(100px);
background: rgba(255, 0, 0, 0.5);
}
#back_face {
transform: translateX(-100px) translateY(-100px) translateZ(-100px);
background: rgba(255, 0, 255, 0.5);
}
#right_face {
transform: translateY(-100px) rotateY(90deg);
background: rgba(255, 255, 0, 0.5);
}
#left_face {
transform: translateY(-100px) translateX(-200px) rotateY(90deg);
background: rgba(0, 255, 0, 0.5);
}
#top_face {
transform: translateX(-100px) translateY(-200px) rotateX(90deg);
background: rgba(0, 255, 255, 0.5);
}
#bottom_face {
transform: translateX(-100px) rotateX(90deg);
background: rgba(255, 255, 255, 0.5);
}
.cube {
transform: rotateX(90deg) rotateY(90deg);
}
<html>
<head>
<title>3D Cube in PureScript</title>
<link rel="stylesheet" type="text/css" href="css/cube_ref.css" />
<script type="text/javascript" src=../js/jquery-3.2.1.min.js></script>
</head>
<body style="width: 100%; height:100%;">
<!-- Wrapper for the cube -->
<div id="cube-wrapper">
<div class="cube">
<!-- A div for each face of the cube -->
<div id="front_face" class="face"></div>
<div id="right_face" class="face"></div>
<div id="back_face" class="face"></div>
<div id="left_face" class="face"></div>
<div id="top_face" class="face"></div>
<div id="bottom_face" class="face"></div>
</div>
</div>
</body>
<script type="text/javascript" src=js/cube.js></script>
</html>
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).
xy 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
.
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.
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;
}
链接地址: http://www.djcxy.com/p/81816.html
上一篇: 基于四元数的旋转和枢轴位置
下一篇: 在固定轴上旋转CSS立方体