簡體   English   中英

計算具有左上角變換原點的旋轉矩形坐標

[英]Calculate rotated rectangle coordinates with top left transform origin

我試圖用左上變換原點繪制這個旋轉矩形的 4 個角。 現在,紅色矩形完全按照我想要的方式繪制,但我正在嘗試繪制四個角,但正如您所見,坐標似乎發生了偏移,但我不明白為什么。 我怎樣才能更正綠色角坐標,使它們與紅色矩形相匹配。

紅色矩形的 x 和 y 坐標對應於旋轉后的矩形左上角

 function radians(deg) { return deg * (Math.PI / 180); } function getPointRotated(X, Y, R, Xos, Yos) { var rotatedX = X + Xos * Math.cos(radians(R)) - Yos * Math.sin(radians(R)); var rotatedY = Y + Xos * Math.sin(radians(R)) + Yos * Math.cos(radians(R)); return { x: rotatedX, y: rotatedY }; } const rect = { x: 100, y: 100, width: 150, height: 50, rotation: 45 }; const htmlRect = document.createElement("div"); htmlRect.style.height = rect.height + "px"; htmlRect.style.width = rect.width + "px"; htmlRect.style.position = "absolute"; htmlRect.style.background = "red"; htmlRect.style.transformOrigin = "top left"; htmlRect.style.transform = `translate3d(${rect.x}px,${rect.y}px,0) rotate(${rect.rotation}deg)`; document.body.appendChild(htmlRect); function drawPoint(point) { const el = document.createElement("div"); el.style.height = 10 + "px"; el.style.width = 10 + "px"; el.style.position = "absolute"; el.style.background = "green"; el.style.transformOrigin = "center center"; el.style.transform = `translate3d(${point.x}px,${point.y}px,0)`; document.body.appendChild(el); } var pointRotated = []; pointRotated.push( getPointRotated( rect.x, rect.y, rect.rotation, -rect.width / 2, rect.height / 2 ) ); pointRotated.push( getPointRotated( rect.x, rect.y, rect.rotation, rect.width / 2, rect.height / 2 ) ); pointRotated.push( getPointRotated( rect.x, rect.y, rect.rotation, -rect.width / 2, -rect.height / 2 ) ); pointRotated.push( getPointRotated( rect.x, rect.y, rect.rotation, rect.width / 2, -rect.height / 2 ) ); for (let point of pointRotated) { drawPoint(point); }

繞原點旋轉遵循等式

X = c x - s y
Y = s x + c y

其中c , s是角度的余弦和正弦。

圍繞任意點(u, v)的旋轉是

X = c (x - u) - s (y - v) + u
Y = s (x - u) + c (y - v) + v

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM