Using transformation matrix in KineticJS

旧时模样 提交于 2019-12-05 18:10:20

The Kinetic.Transform class can be used to calculate rotation, scale and offset from a given transformation matrix. Set the m attribute of Kinetic.Transform to the transformation matrix, then use the transform object to calculate rotation, scale and translation. Rotation, scale and translation can then be applied to any Kinetic.Node

Translation is given directly by the last two items in the matrix.

If you acquire a transformation from elsewhere, you can apply it to a Kinetic.Transform like this:

var tf = new Kinetic.Transform();
tf.m = [Math.sqrt(2), Math.sqrt(2), -3/2*Math.sqrt(2), 3/2*Math.sqrt(2), 4, 5];

Translation is the easiest. it is given by the last two elements: 4 in X direction, 5 in Y direction. There is also a method to get it.

var translation = tf.getTranslation();

You can get the scale from the transformation matrix:

var m = tf.getMatrix(); // or tf.m
var scaleX = Math.sqrt(m[0]*m[0] + m[1]*m[1]);
var scaleY = Math.sqrt(m[2]*m[2] + m[3]*m[3]);

Don't forget that the image can be flipped over the X or Y axis, or both. Calculate the determinant to take that into account:

if(m[0]*m[3] - m[1]*m[2] < 0){
    scaleY = -scaleY;
}

Adjust the sign of the scales to get the rotation more easily:

if(m[0] < 0){
    scaleX = -scaleX;
    scaleY = -scaleY;
}

Now the last one, rotation. You can get that by using Math.asin or Math.acos, but you must take the quadrant of the rotation angle into account. This is one way to solve it:

var angle = Math.acos(m[3] / scaleY);
if(m[2]/scaleY > 0){
    angle = -angle;
}

Note that the order in which to apply the different transformations is important. If you use the method explained above, first apply translation, then rotation, then scale.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!