How to convert CSS transform matrix back to its component properties

前端 未结 1 1666
灰色年华
灰色年华 2021-02-14 06:46

I have obtained a CSS transform matrix of an element by using getComputedStyle() method as follows.

var style = window.getComputedStyle(elem1, null)         


        
1条回答
  •  生来不讨喜
    2021-02-14 06:50

    Yes, it's possible to do that!

    The parameters to matrix come in this order: matrix(scaleX(),skewY(),skewX(),scaleY(),translateX(),translateY())

    Read more about it here

    If you want to retrieve the numbers from that string (matrix(1,0,0,1,720,290) you could use this regex:

    style = window.getComputedStyle(elem1, null);
    trans = style.transform;
    numberPattern = /-?\d+\.?\d*/g;
    
    values = trans.match( numberPattern );
    

    This will return the following array:

    ["1", "0", "0", "1", "720", "290"]
    

    Edit after comments

    The values returned in the window.getComputedStyle are the computed values (i.e. the percentages you used are being parsed to pixel values). You can reverse that calculation, but you need to know what the percentage is using to figure out how many pixels it should be.

    Enter CSS3 Transforms

    One interesting thing about CSS transforms is that, when applying them with percentage values, they base that value on the dimensions of the element which they are being implemented on, as opposed to properties like top, right, bottom, left, margin, and padding, which only use the parent's dimensions (or in case of absolute positioning, which uses its closest relative parent). Source

    if you use the following calculation, you should be able to get the percentages you used:

    style = window.getComputedStyle(elem1, null);
    trans = style.transform;
    numberPattern = /-?\d+\.?\d+|\d+/g;
    
    values = trans.match( numberPattern );
    
    computedTranslateX = values[4];
    computedTranslatey = values[5];
    
    xPercentage = (computedTranslateX / elem1.offsetWidth) * 100;
    yPercentage = (computedTranslateY / elem1.offsetHeight) * 100;
    

    0 讨论(0)
提交回复
热议问题