2012-05-15 11 views
6

Tengo un elemento de cubo girado y traducido en un espacio 3D.Cómo aplicar ingeniería inversa a una transformación webkit matrix3d ​​

Quiero averiguar solo la parte rotateY de esta transformación en un momento dado. es posible?

tengo:

var cube = document.getElementById("cube"); 
var transform = getComputedStyle(cube).webkitTransform; 

//the value of transform is: 
// matrix3d(-1, 0, 0.00000000000000012246467991473532, 0, 
//   0, 1, 0, 0, 
//   -0.00000000000000012246467991473532, 0, -1, 0, 
//   0, 0, 0, 1) 

Ayuda? :-)

+0

conseguir y valor de la transformación? es posible que desee echar un vistazo a translate(). que convierte la forma de la matriz en valor. más sobre esto aquí [traducir transformación] (https://developer.mozilla.org/en/CSS/transform-function#translate()) –

+0

Tal vez no siguen, pero estoy atascado con este Matrix3D, la transformación me está aplicando el código de otra persona. Solo estoy tratando de ver si puedo regresar a SOLO la rotación –

+0

No entendí bien. Pensaste que querías usar el valor de transformar para hacer algo. descarta el comentario. He encontrado una función en este enlace [Leer getRotationDegrees] (http://stackoverflow.com/questions/3336101/css3-animation-on-transform-rotate-way-to-fetch-current-deg-of-the-rotating- el). Y lea en el enlace de arriba para saber qué valor pertenece a Y. y use la forma en que usan la función para obtener Y degree. Voy a leer sobre esto más tarde si no has recibido la respuesta. lo siento por no ser lo suficientemente útil. en mi camino al trabajo. :) –

Respuesta

4

Si su objeto solo se gira sobre Y, entonces sí, la rotación es simple de calcular - es el arccos of Matrix elements 1,1 o 3,3 o el arsin de - (elemento 3,1) o el arcsin del elemento 1 , 3. En su ejemplo específico, es aproximadamente 180 grados. Si las rotaciones son más que solo el eje y, entonces debe comenzar a rastrear las rotaciones anteriores y puede volverse más desordenado.

Su traducción será simplemente la fila inferior de la matriz de salida, 0,0,0 en este caso.

ver ejemplos en http://www.inversereality.org/tutorials/graphics%20programming/3dwmatrices.html

4

Puede recuperar información de transformación con la función "nueva WebKitCSSMatrix". Por ejemplo:

var matrix = new WebKitCSSMatrix($('#element').css('-webkit-transform')); 
var translateZ = matrix.m43; 

Cada parte de la matriz es explicar aquí: http://9elements.com/html5demos/matrix3d/ Puede recuperar las propiedades más complexe como rotationX, para la matriz 3d con las matemáticas desastre:

var rotationX = Math.acos(matrix.a) * (180/Math.PI); 
var rotationY = Math.asin(matrix.b) * (180/Math.PI); 
2

función dada determina rotation*, transform* y scale para el elemento DOM dado cross-browser.

Si quieres algo más, o encontrar los fallos en las matemáticas, es una discusión sobre math.stackexchange.com

Probado en los navegadores enumeran en http://caniuse.com/transforms3d:

var reverseEngineerTransform3d = function (domElement, parameterName) { 

     parameterName = parameterName.toLowerCase(); 

     var computedStyle = window.getComputedStyle(domElement), 
      matrixStyle = computedStyle.transform || computedStyle.WebkitTransform || computedStyle.MozTransform || computedStyle.msTransform || computedStyle.OTransform; 

     if (matrixStyle) { 
      matrixStyle = matrixStyle.trim(); 
     } 

     if (matrixStyle === 'none') { 
      if (parameterName.indexOf('rotate') === 0) { 
       return '0deg'; 
      } else if (parameterName.indexOf('translate') === 0) { 
       return '0px'; 
      } else if (parameterName === 'scale') { 
       return 1; 
      } else { 
       throw "Unsupported 3D parameter " + parameterName; 
      } 
     } 

     else if (!matrixStyle || matrixStyle.substr(0, 9) !== 'matrix3d(') { 
      //return something or die ????? 
      throw "Something is wrong with 3D transform style. Probably no style applied at all OR unknown CSS3 vendor OR unknown/unsupported 3D matrix representation string OR CSS3 3D transform is not fully supported in this browser"; 
     } 

     var matrix = window.WebKitCSSMatrix && (new WebKitCSSMatrix(matrixStyle)) || 
       window.MozCSSMatrix && (new MozCSSMatrix(matrixStyle)) || 
       window.MsCSSMatrix && (new MsCSSMatrix(matrixStyle)) || 
       window.OCSSMatrix && (new OCSSMatrix(matrixStyle)) || 
       window.CSSMatrix && (new CSSMatrix(matrixStyle)); // sorry 4 copy-paste my friends 

     if (!matrix || isNaN(matrix.a) || isNaN(matrix.b) || isNaN(matrix.c) || isNaN(matrix.m41) || isNaN(matrix.m42) || isNaN(matrix.m43) || isNaN(matrix.m11)) { 
      throw "Could not catch CSSMatrix constructor for current browser, OR the constructor has returned a non-standard matrix object (need .a, .b, .c and mXX numerical properties to work)"; 
     } 


     // todo: giving a parameters array (and returning an array) is a good idea, or we could return everything if no parameters given 

     switch (parameterName) { 

      case 'rotatey': // in degrees 
       return Math.acos(matrix.m11)*180/Math.PI * (matrix.m13 > 0 ? -1 : 1) + 'deg'; 

      case 'rotatex': // in degrees 
       return Math.asin(matrix.m22)*180/Math.PI + 'deg'; 

      case 'rotatez': // in degrees 
       throw "TODO: Sorry, math people. I really need help here! Please implement this case for me. This will help you: http://9elements.com/html5demos/matrix3d/"; 

      case 'translatex': // in pixels 
       return matrix.m41 + 'px'; 

      case 'translatey': // in pixels 
       return matrix.m42 + 'px'; 

      case 'translatez': // in pixels 
       return matrix.m43 + 'px'; 

      case 'scale': // no units 
       if (matrix.m11 === matrix.m22 && matrix.m22 === matrix.m33) { 
        return matrix.m11; 
       } else { 
        throw "I'm not so smart to calculate scale from this matrix"; 
       } 

      // todo: anything else? skew ???? 

      default: 
       throw "This function accepts 3d-parameter name (case-insensitive string) as the second argument. Currently supported: 'rotate[xyz]', 'translate[xyz]', 'scale'. This parameter is unsupported: " + parameterName; 
     } 
    }; 
+1

Uno con mejores habilidades matemáticas puede ampliar las posibilidades de funciones. Una vez que tenemos la matriz, podemos realizar ingeniería inversa de una gran cantidad de cosas – Dan

+0

// TODO: un buen artículo que procesará pronto: http://css-tricks.com/get-value-of-css-rotation-through- javascript / – Dan

Cuestiones relacionadas