JSFiddle - React, Tailwind, and code Playground
by Dragos Petre
HTML
<div id="box">
</div>
<div id="box2">
</div>
CSS
#box {background-color:red;
width:200px;
height:200px;
left:100px;
top:100px;
position:absolute;
z-index:2;
transform:rotate(20deg)}
#box2 {background-color:blue;
width:200px;
height:200px;
left:100px;
top:100px;
position:absolute;
transform:rotate(0deg)}
JavaScript
$(document).ready(function(){
oldleft = parseInt($('#box').css('left').replace("px", ""));
oldtop = parseInt($('#box').css('top').replace("px", ""));
width = parseInt($('#box').css('width').replace("px", ""));
height = parseInt($('#box').css('height').replace("px", ""));
$.fn.rotationInfo = function() {
var el = $(this),
tr = el.css("-webkit-transform") || el.css("-moz-transform") || el.css("-ms-transform") || el.css("-o-transform") || '',
info = {rad: 0, deg: 0};
if (tr = tr.match('matrix\\((.*)\\)')) {
tr = tr[1].split(',');
if(typeof tr[0] != 'undefined' && typeof tr[1] != 'undefined') {
info.rad = Math.atan2(tr[1], tr[0]);
info.deg = parseFloat((info.rad * 180 / Math.PI).toFixed(1));
}
}
return info;
};
function rotatedTopLeft(x,y,width,height,rotationAngle){
// get the center of the rectangle (==rotation point)
var cx=x+width/2;
var cy=y+height/2;
// calc the angle of the unrotated TL corner vs the center point
var dx=x-cx;
var dy=y-cy;
var originalTopLeftAngle=Math.atan2(dy,dx);
// Add the unrotatedTL + rotationAngle to get total rotation
var rotatedTopLeftAngle=originalTopLeftAngle+rotationAngle;
// calc the radius of the rectangle (==diagonalLength/2)
var radius=Math.sqrt(width*width+height*height)/2;
// calc the rotated top & left corner
var rx=cx+radius*Math.cos(rotatedTopLeftAngle);
var ry=cy+radius*Math.sin(rotatedTopLeftAngle);
// return the results
return({left:Math.round(rx,0),top:Math.round(ry,0)});
}
response = rotatedTopLeft(oldleft,oldtop,width,height,$('#box').rotationInfo().rad);
alert('new left '+response['left']+'new top'+response['top']);
});