JSFiddle - React, Tailwind, and code Playground
by unloco
HTML
<button>Increase width and height</button>
<div class="object">
</div>
<div class="object-initial">
</div>
CSS
.object {
position: absolute;
outline: 1px solid black;
transform: rotate(20deg);
}
.object-initial {
position: absolute;
outline: 1px dashed black;
transform: rotate(20deg);
top: 50px;
left: 50px;
width: 100px;
height: 100px;
}
JavaScript
var h = 100;
var w = 100;
var l = 50;
var t = 50;
var r = 30;
var obj = document.querySelector('.object');
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
console.log('click');
var increment = 5;
var offset = getCorrection(w, h, increment, increment, r);
h += increment;
w += increment;
t += offset.top;
l -= offset.left;
updateElement();
});
function updateElement() {
obj.style.left = l + 'px';
obj.style.top = t + 'px';
obj.style.width = w + 'px';
obj.style.height = h + 'px';
}
function getCorrection(init_w, init_h, delta_w, delta_h, angle) {
//Convert angle from degrees to radians
angle = angle * Math.PI / 180
//Get position after rotation with original size
var x = -init_w / 2;
var y = init_h / 2;
var new_x = y * Math.sin(angle) + x * Math.cos(angle);
var new_y = y * Math.cos(angle) - x * Math.sin(angle);
var diff1 = { left: new_x - x, top: new_y - y };
var new_width = init_w + delta_w;
var new_height = init_h + delta_h;
//Get position after rotation with new size
var x = -new_width / 2;
var y = new_height / 2;
var new_x = y * Math.sin(angle) + x * Math.cos(angle);
var new_y = y * Math.cos(angle) - x * Math.sin(angle);
var diff2 = { left: new_x - x, top: new_y - y };
//Get the difference between the two positions
var offset = { left: diff2.left - diff1.left, top: diff2.top - diff1.top };
return offset;
}
updateElement();