我有一个“基本”引用矩形(红色)
在旋转的 div (#map) 内,我需要一个克隆矩形(黄色),它必须与“基本”矩形具有相同的大小和位置,独立于其父级 (#map) 旋转。
这就是我到目前为止的情况,欢迎任何帮助。
http://codepen.io/christianpugliese/pen/oXKOda
var controls = { degrees: 0, rectX:125, rectY:55 };
var wBounds = document.getElementById("wrapper").getBoundingClientRect(),
mapBounds = document.getElementById("map").getBoundingClientRect(),
rectBounds = document.getElementById("rect").getBoundingClientRect();
var _x = ((mapBounds.width - wBounds.width) / 2) + $('#rect').position().left,
_y = ((mapBounds.height - wBounds.height) / 2) + $('#rect').position().top;
$('#rect').css({top: controls.rectY+'px', left:controls.rectX+'px'});
$('#mapRect').width(rectBounds.width);
$('#mapRect').height(rectBounds.height);
$('#mapRect').css({top: _y+'px',
left:_x+'px',
'transform': 'rotate('+ Math.round(-controls.degrees) +'deg)'});
$('#map').css('transform', 'rotate('+ Math.round(controls.degrees) +'deg)');
最佳答案
由于您在相反方向上将#mapRect
旋转了相等的量,因此您的旋转/方向是正确的,但不是原点。 transform-origin
将是 #mapBounds
的中心,但相对于 #rect
;
你的笔叉:http://codepen.io/MisterCurtis/pen/vNBYZJ?editors=101
由于发生了一些舍入/子像素定位,黄色矩形无法完美对齐像素。
function updateUI(){
var _x = ((mapBounds.width - wBounds.width) / 2) + $('#rect').position().left,
_y = ((mapBounds.height - wBounds.height) / 2) + $('#rect').position().top,
_ox = mapBounds.width/2 - _x, // origin x
_oy = mapBounds.height/2 - _y; // origin y
...
$('#mapRect').css({
'transform-origin': _ox + 'px ' + _oy + 'px', // now it rotates by the bounds
top: _y + 'px',
left: _x + 'px',
'transform': 'rotate(' + Math.round(-controls.degrees) + 'deg)'
});
}
编辑:更新了pen 。您必须放弃使用矩形,而使用多边形。这样你就可以使用像https://github.com/ahmadnassri/google-maps-polygon-rotate这样的插件了沿 map 中心执行旋转。
关于javascript在旋转的元素中找到相同的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32231620/