转换矩阵值后,如何从 style.transform 旋转得到正确的度数?

How do I get the correct degress from style.transform rotate after I converted the matrix values?

我正在尝试从 div 获取旋转度数,我旋转以创建线条图案。

直到现在我才 运行 遇到了问题。我需要 div 的旋转(度)来计算下一行需要出现的位置。但是,当我尝试使用 style.transform 从 div 获取值并转换矩阵值时,我仍然得到错误的度数。

在我的测试案例中,我有一个 div 旋转了 150 度,但我得到了 30 度,不幸的是,这对我不起作用。请帮忙,如何找回 150deg 值?

代码如下:

HTML:

<div class="linesBox" id="linesBox">
    <div class="line1 lines" id="line1" style="float: left;
    margin: 200px 0 0 100px;
    position: fixed;
    border-top:0.5px solid black;
    width: 100px;
    transform: rotate(150deg);"></div> 
    <!-- <div class="line2 lines" id="line1" style="float: left;
    margin: 174px 0 0 193.3px;
    position: fixed;
    border-top:0.5px solid black;
    width:100px;
    transform: rotate(0deg);"></div> -->



</div>

JavaScript:

const linesBox = document.getElementById('linesBox');

let lastLineWidth;
let angle;
let lineWidthCount;
let lineHeightCount;

function createLines(){

//Last line div in a var and a var to get the computated value 
let lastLine = linesBox.lastElementChild;
var st = window.getComputedStyle(lastLine, null);

//Get the width and angle of the last line and place them in a var
lastLineWidth = parseFloat(lastLine.style.width);
lastLineXPos = parseFloat(lastLine.style.marginLeft);
lastLineYPos = parseFloat(lastLine.style.marginTop);
let lastLineAngle = st.getPropertyValue("transform");
console.log(lastLineWidth, lastLineXPos, lastLineYPos);

//Get and map the Matrix value from transform rotate() and set it to lastLineAngle
var values = lastLineAngle.split('(')[1],
    values = values.split(')')[0],
    values = values.split(',');

//Set each value of the matrix values to a var
let a = values[0]; 
let b = values[1]; 
let c = values[2];
let d = values[3]; 

//Take the correc value from the matrix values and place it in the formula and save the outcome in a var
angle = Math.round(Math.asin(b) * (180/Math.PI));
console.log(angle);

//Calculate margin left starting position for the next line
//Get sin en cos values by angle 
let yChangeOne = lastLineWidth * Math.sin(angle / 180 * Math.PI) / 2;
let xChangeOne = parseFloat(lastLineWidth - lastLineWidth * Math.cos(angle / 180 * Math.PI)) / 2;


// let yChangeOne = lastLineWidth * sinOutcome / 2;
// let xChangeOne = lastLineWidth - lastLineWidth * cosOutcome; 
console.log(yChangeOne, xChangeOne);

let newYPos;
let newXPos;

if( angle <= 89 && angle >= 1 ){
    newYPos = lastLineYPos + yChangeOne;

} else if ( angle >= 91 && angle <= 179 ){
    newYPos = lastLineYPos - yChangeOne;
}
console.log(newYPos);} 

  //Get the start position for the next line  
  createLines();

角度应该 return 150 度而不是 30 度,否则我的 if 语句将不起作用。请帮助:)

30°和150°的正弦相同。您还需要考虑余弦。使用

而不是 Math.asin(b)
Math.atan2(b, a)

顺便说一句,如果你只是计算角度再计算它的正弦和余弦,那么就省去这一步(Math.sin(angle...))。你那里有正弦和余弦,所以就用它们。