JSFiddle - React, Tailwind, and code Playground
HTML
<div id="rect1"></div>
<div id="rect2"></div>
CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#rect1 {
position: absolute;
width: 100px;
aspect-ratio: 2/1;
background: red;
opacity: 0.5;
/* transform: rotate(50deg); */
}
#rect2 {
position: absolute;
width: 200px;
aspect-ratio: 2/1;
border: 1px solid black;
opacity: 0.5;
}
JavaScript
const cont= document.querySelector('#rect2');
const rot= document.querySelector('#rect1');
const hRot = rot.offsetHeight, h = cont.offsetHeight;
const wRot = rot.offsetWidth, w = cont.offsetWidth;
let t=0;
const anim= setInterval(rotate, 10);
function rotate(){
rot.style.transform = "rotate(-" + t + "deg)";
update(t);
t += 0.1;
t = t % 360;
}
function update(T){
T = T % 180;
T = T > 90 ? 180 - T : T;
const phi = degToRad(T),
sin_phi = Math.sin(phi),
cos_phi = Math.cos(phi),
ratio1 = (w * cos_phi + h * sin_phi) / wRot,
ratio2 = (w * sin_phi + h * cos_phi) / hRot,
ratio = Math.max(ratio1, ratio2);
rot.style.transform += " scale(" + ratio + ")";
}
function degToRad(angle){
return angle * Math.PI / 180;
}