简体   繁体   中英

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.

This is where I am so far, any help would be welcoming.

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. The transform-origin would be the center of the #mapBounds , but relative to the #rect ;

Fork of your pen: 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. This way you can use a plugin like https://github.com/ahmadnassri/google-maps-polygon-rotate to perform the rotation along the map center.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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