javascript在旋转的元素中找到相同的位置

标签 javascript jquery

我有一个“基本”引用矩形(红色)

在旋转的 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)');

enter image description here

最佳答案

由于您在相反方向上将#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/

相关文章:

javascript - 简单的正则表达式Excel提取

javascript - 如何从远处找到latlong?

javascript - 在最少的运行中有效地查找并返回多个值的数组位置

javascript - jquery链淡入淡出方法不起作用

jquery - 为什么 $() 不起作用但 jQuery() 起作用?

javascript - Reactify、Browserify 和 Gulp : TypeError: Object #<Transform> has no method 'transform'

javascript - 防止固定位置对象在特定位置随页面滚动

javascript - opencart 联系页面验证码未出现

javascript - 如何使用javascript一一删除附加元素

jquery - 为什么表单操作页中的结构键值显示两次,如 "Submit,Submit"?