繁体   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