简体   繁体   English

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

[英]javascript find same position in rotated element

I have a "base" reference rect (red) 我有一个“基本”参考矩形(红色)

Inside a rotated div (#map), I need a clone rect (yellow), it has to be same size and position of "base" rect, independent of its parent (#map) rotation. 在旋转的div(#map)内,我需要一个克隆rect(黄色),它的大小和位置必须与“基本” rect相同,而与父级(#map)的旋转无关。

This is where I am so far, any help would be welcoming. 到目前为止,这是我的所在地,欢迎任何帮助。

http://codepen.io/christianpugliese/pen/oXKOda 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)');

在此处输入图片说明

Since you're rotating the #mapRect an equal amount in the opposite direction you're getting rotation/orientation right but not the origin. 由于您将#mapRect沿相反的方向旋转相等的量,因此您将获得正确的旋转/方向而不是原点。 The transform-origin would be the center of the #mapBounds , but relative to the #rect ; transform-origin将是#mapBounds的中心,但相对于#rect

Fork of your pen: http://codepen.io/MisterCurtis/pen/vNBYZJ?editors=101 笔叉: http : //codepen.io/MisterCurtis/pen/vNBYZJ?editors=101

Since there is some rounding/subpixel positioning happening the yellow rect doesn't align pixel perfect. 由于存在一些舍入/子像素定位,因此黄色矩形无法完美对齐像素。

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)'
  });
}

Edit: Updated the pen . 编辑:更新了 You'll have to ditch using Rectangle and instead use Polygon. 您将不得不使用Rectangle来代替,而使用Polygon。 This way you can use a plugin like https://github.com/ahmadnassri/google-maps-polygon-rotate to perform the rotation along the map center. 这样,您可以使用https://github.com/ahmadnassri/google-maps-polygon-rotate这样的插件沿地图中心执行旋转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM