如何将变换原点设置为元素上的特定点?

How to set the transform origin to a specific point on the element?

在这个例子中,我想从底部旋转锤子,所以有没有办法准确知道元素上特定点的正确坐标,或者我应该随机尝试不同的点吗?

svg {
  width: 50%;
}

.hammer-icon {
  transform-origin: 200px 50px;
  transition: transform .3s ease-out;
}

.hammer:hover .hammer-icon {
  transform: rotate(45deg);
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -50 400 200">
  <g class="hammer">
    <circle class="hammer-bg" fill="#FFD466" cx="200" cy="50" r="90"></circle>
    <path class="hammer-icon" fill="#FFFFFF" d="M262,32.9l-6.7-6.9c-1.4-1.4-3.6-1.4-5-0.1l-2.8,2.8l-14.6-15c-7-7.2-20.3-18.5-30.1-16.4
      c-1.6,0.3-5.6,3.1-5.6,3.1l19,19.5l-26.3,25.6l-1.5-1.6c-1.4-1.4-3.6-1.4-5-0.1l-39.3,38.3c-1.4,1.4-1.4,3.6-0.1,5l14.4,14.8
      c1.4,1.4,3.6,1.4,5,0.1l39.3-38.3c1.4-1.4,1.4-3.6,0.1-5l-1.5-1.6l26.3-25.6l8.3,8.5l-2.8,2.8c-1.4,1.4-1.4,3.6-0.1,5l6.7,6.9
      c1.4,1.4,3.6,1.4,5,0.1l17.3-16.9C263.3,36.5,263.4,34.3,262,32.9z"></path>
  </g>
</svg>

如果您知道要从特定点旋转,即:左下角。您可以使用以下关键字应用变换原点;

.hammer-icon {
    // x-offset y-offset 
    transform-origin: left bottom;
}

进一步参考:https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin

要使 transform-origin 点相对于元素,您需要使用 transform-box: fill-box;

Chrome 还不支持 属性 (CSS transform-box - Chrome Platform Status), but luckily (yet wrongfully) Chrome sets the transform-origin relative to the element if you use percentages instead of pixels (https://css-tricks.com/transforms-on-svg-elements/)。

因此,要制作适用于大多数 *) 现代浏览器的内容,请使用 transform-box: fill-box;transform-origin: xx% yy%;

.hammer-icon {
    transform-origin: 15% 80%;
    transform-box: fill-box;
    ...
}

https://jsfiddle.net/L1790vzo/8

*) IE/Edge 根本不支持 CSS 对 SVG 元素的转换。
*) 在 Chrome v64 和 Opera v51

中的适当支持

变换原点:[x][y]

将 x 和 y 分别替换为百分比值,例如中间位置为 50%,开始位置为 0%,结束位置为 100%。为了让大家一劳永逸地理解这一点,我做了一支笔。

我在这里写了一篇完整的文章:https://medium.com/@RajaRaghav/understanding-css-transform-origin-property-2ef5f8c50777 带有说明性的例子