0

试图实现从所有 4 个角调整盒子大小的能力。这很简单,但我还希望能够旋转并保持锚点保持在原位(就像任何像样的照片编辑软件一样)。我可能想多了,但事实证明需要一些复杂的触发才能像这样锁定锚点:

http://jsfiddle.net/andrewplummer/W8tyB/1/

需要明确的是,代码中实际上并没有多个框......不同的框应该代表一个从不同角落调整为不同大小的单个框。

这个例子在 45 度时非常简单,但我最终想要的是能够获得任何尺寸框(当然也是矩形,不仅仅是正方形)的位置(左,上)在任何锚点处以任何旋转按住在上面。

欢迎直接帮助,但如果有任何关于如何制定问题来回答这个问题的博客文章,它可能会更有帮助!

完整代码:

<div id="box1"></div>

<!-- Resizing to 40x40 with the anchor at the top -->
<div id="box2"></div>
<!-- Resizing to 30x30 with the anchor at the top -->
<div id="box3"></div>

<!-- Resizing to 40x40 with the anchor at the left -->
<div id="box4"></div>
<!-- Resizing to 30x30 with the anchor at the left -->
<div id="box5"></div>

#box1 {
  position: absolute;
  top: 50px;
  left: 50px;
  width: 100px;
  height: 100px;
  background: rgba(0,0,0,0.2);
  -webkit-transform: rotateZ(45deg);
}

#box2 {
  position: absolute;
  top: 38px;
  left: 79px;
  width: 40px;
  height: 40px;
  background: rgba(255,0,0,0.2);
  -webkit-transform: rotateZ(45deg);
}

#box3 {
  position: absolute;
  top: 34px;
  left: 87px;
  width: 30px;
  height: 30px;
  background: rgba(255,0,0,0.2);
  -webkit-transform: rotateZ(45deg);
}

#box4 {
  position: absolute;
  top: 79px;
  left: 38px;
  width: 40px;
  height: 40px;
  background: rgba(0,0,255,0.2);
  -webkit-transform: rotateZ(45deg);
}

#box5 {
  position: absolute;
  top: 84px;
  left: 36px;
  width: 30px;
  height: 30px;
  background: rgba(0,0,255,0.2);
  -webkit-transform: rotateZ(45deg);
}
4

1 回答 1

0

好的,我想通了...在我的情况下,它并不像需要矩阵那么复杂(没有倾斜、缩放或平移...我想要的只是高度/宽度和旋转),结果证明它更简单比我想象的要好。

最后,对我有用的代码是,我知道所涉及的锚点,计算从锚点到应用旋转的矩形中心的距离,然后在不应用旋转的情况下移动到左上角。

var offsetX  = rectangleWidth / 2;
var offsetY  = rectangleHeight / 2;

// If we are on the "right/east" side then to get to the
// center the X value needs to be inverted. Likewise for
// the Y value for "bottom/south".
if(anchor.type === 'ne' || anchor.type === 'se') {
  offsetX *= -1;
}
if(anchor.type === 'sw' || anchor.type === 'se') {
  offsetY *= -1;
}

// Get the distance to the center and apply rotation.
var distanceToCenter = new Point(offsetX, offsetY).rotate(rectangle.rotation);
// Distance to the top left corner is always the same regardless of the rotation.
var distanceToTopLeftCorner = new Point(-rectangleWidth / 2, -rectangleHeight / 2);

// And that's it! Getting the x/y position of the rotated rectangle is simply a matter
// of moving to the center of the rectangle (taking rotation into regard), then moving
// to the non-rotated upper left corner (which would be the same as of the rectangle
// had no rotation applied)
var position = anchor.position.add(distanceToCenter).add(distanceToTopLeftCorner);
于 2013-09-21T14:27:06.090 回答