Home > Net >  How to make rotate pivot with svg element's center
How to make rotate pivot with svg element's center

Time:07-01

Following is my code, I have set line center as rotate pivot transform-origin 50px 50px, but the line doesn't rotate with its center

<!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  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" >
  </path>
</svg>

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

CodePudding user response:

I find the reason, the reason is I put transform-origin in keyframe it's frame 0 transform-origin is default but in frame transform-origin is 50px 50px, it cause element transform, so the solution is set transform-origin in element class not keyframe; following is correct code

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

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

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

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

CodePudding user response:

I believe you mean you want it to spin around the center? Maybe rethink the approach - make a div with a line up it's center and then just rotate the div and set overflow to hidden ? You could even use an image with a line up its top center and make that image spin. Check out this code.

HTML:

<div >
  <div >
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
  </div>
  <div >
  </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 to see it in action: https://codepen.io/adamdolson/pen/vYREQMY

  • Related