繁体   English   中英

如何使用svg元素的中心旋转枢轴

[英]How to make rotate pivot with svg element's center

以下是我的代码,我已将 line center 设置为 rotate pivot transform-origin 50px 50px ,但该线不随其中心旋转

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <!-- disable request favicon-->
  <link rel="icon" href="data:;base64,iVBORw0KGgo=">
  <!--mobile friendly-->
  <meta name="viewport" content="width=device-width, user-scalable=yes">
</head>
<body>
<style>
  .c {
    transform: translate(200px, 200px);
  }

  .it {
    animation: spin 2s linear infinite;
  }

  @keyframes spin {
    /*50% {*/
    /*  transform: rotate(180deg);*/
    /*}*/
    50% {
      transform-origin: 50px 50px;
      transform: rotate(360deg);
    }
  }

</style>
<svg class="c" width="100" height="100">
  <!--  <line x1="50" y1="50" x2="50" y2="100" stroke="black"/>-->
  <path d="M 0 50 L 100 50" stroke="black" class="it">
  </path>
</svg>

<script type="module">
</script>
</body>
</html>

我找到了原因,原因是我将transform-origin放在关键帧中,它的第0帧transform-origin是默认的,但是在帧中transform-origin是50px 50px,它会导致元素变换,所以解决方案是在元素类中设置transform-origin not关键帧; 以下是正确的代码

<style>
  .c {
    transform: translate(200px, 200px);
  }

  .it {
    animation: rotate 2s linear infinite;
    transform-origin: 50px 50px;
  }

  @keyframes rotate {
    100% {
      transform: rotate(360deg);
    }
  }

</style>
<svg class="c" width="100" height="100">
  <path d="M 0 50 L 100 50" stroke="black" class="it"></path>
</svg

我相信你的意思是你想让它围绕中心旋转? 也许重新考虑这种方法 - 制作一个 div 与它的中心对齐,然后旋转 div 并将溢出设置为 hidden ? 您甚至可以使用顶部中心对齐的图像并使该图像旋转。 查看此代码。

HTML:

<div class="div1">
  <div class="div2">
    <div class="div3">
    </div>
    <div class="div4">
    </div>
    <div class="div3">
    </div>
  </div>
  <div class="div2">
  </div>
</div>

CSS:

.div1 {
  height: 400px;
  width: 400px;
  background-color: red;
  animation-name: spin;
  animation-duration: 3000ms;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  overflow-x: hidden;
  overflow-y: hidden;
}
.div2 {
  height: 50%;
  width: 100%;
  background-color: white;
  display: flex;
}
.div3 {
  height: 100%;
  width: 49.5%;
  background-color: white;
}
.div4 {
  height: 100%;
  width: 1%;
  background-color: black;
}
@keyframes spin {
  from {transform:rotate(0deg);}
  to {transform:rotate(360deg);}
}

Codepen 来看看它的实际效果: https ://codepen.io/adamdolson/pen/vYREQMY

暂无
暂无

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

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