给定rotateX,rotateY和rotateZ,我该如何计算matrix3d?

时间:2015-11-05 05:15:46

标签: javascript css matrix css-transforms

鉴于我有三个转换属性rotateX(20deg) rotateY(30deg)rotateZ(50deg),是否可以计算matrix3d(...)

在此示例中,matrix3d将是:

matrix3d(0.5568,-0.77,0.50,0,0.77,0.6016,0.34,0,-0.5,-0.34,0.8178,0,0,0,0,1);

1 个答案:

答案 0 :(得分:2)

以下是解决matrix3D问题的好方法:https://gist.github.com/f5io/7466669

var str = matrix3d(0.5568,-0.77,0.50,0,0.77,0.6016,0.34,0,-0.5,-0.34,0.8178,0,0,0,0,1),
out = create();
function deg2rad(deg) {
return deg * (Math.PI / 180);
}
function create() {
var out, args = Array.prototype.slice.call(arguments);
if (args.length > 0 && args.length < 16) throw 'Invalid arguments supplied!';
if (args.length === 0) {
    out = new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);
} else {
    out = new Float32Array(args);
}
return out;
}

function fromTransform (str) {
var r = str.match(/([\d.-]+(?!\w))+/g);

return new Array([
    r[0],   r[1],   r[2],   r[3],
    r[4],   r[5],   r[6],   r[7],
    r[8],   r[9],   r[10],  r[11],
    r[12],  r[13],  r[14],  r[15]
]);
}

function rotate(out, deg) {
var rad = deg2rad(deg),
    cos = Math.cos(rad),
    sin = Math.sin(rad);

out[0] = cos;
out[1] = sin;
out[4] = -sin;
out[5] = cos;
}

function rotateX(out, deg) {
var rad = deg2rad(deg),
    cos = Math.cos(rad),
    sin = Math.sin(rad);

out[5] = cos;
out[6] = sin;
out[9] = -sin;
out[10] = cos;
}

function rotateY(out, deg) {
var rad = deg2rad(deg),
    cos = Math.cos(rad),
    sin = Math.sin(rad);

out[0] = cos;
out[2] = sin;
out[8] = -sin;
out[10] = cos;
}

function rotateZ(out, deg) {
Matrix3D.rotate(out, deg);
}

在这里,您可以阅读有关3D的更多信息,以便更好地理解:https://developer.apple.com/library/safari/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Using2Dand3DTransforms/Using2Dand3DTransforms.html#//apple_ref/doc/uid/TP40008032-CH15-SW16