This jQuery function will change the size of the element and make necessary correction to preserve the top-left corner position
JSFiddle
/**
* Resizes rotated set of elements and preserves top-left corner position
* @param {Number} new_width
* @param {Number} new_height
* @param {Number} angle in degrees
* @returns {object} the current jQuery set
*/
$.fn.rotSize = function(new_width, new_height, angle){
//Convert angle from degrees to radians
var angle = angle * Math.PI / 180
$(this).each(function(i, elem){
var $elem = $(elem);
//initial CSS position.
var pos = {left: parseInt($elem.css('left')), top: parseInt($elem.css('top'))};
var init_w = $elem.width();
var init_h = $elem.height();
//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};
//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};
//Calculate the correction
var new_pos = {left: pos.left - offset.left, top: pos.top + offset.top};
//Apply
$elem.css(new_pos);
$elem.css({width: new_width, height: new_height});
});
}
Another useful function:
/**
* Calculate the size correction for resized rotated element
* @param {Number} init_w
* @param {Number} init_h
* @param {Number} delta_w
* @param {Number} delta_h
* @param {Number} angle in degrees
* @returns {object} correction css object {left, top}
*/
$.getCorrection = function(init_w, init_h, delta_w, delta_h, angle){
//Convert angle from degrees to radians
var 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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…