Search code examples
htmlcsssvgrect

How to stroke from top-center of rounded rectangle


I want to make a button out of SVG and replicate the YouTube's autoplay circle. I have been trying to get the stroke to start and end at the top-center, but it will start best at the top-left corner, because when I start changing stroke-dasharry and stroke-dashoffset numbers around it starts to go off at the start or end. I know this would be a lot easier with a circle, but I want to see if this is at all possible. It is starting to seem that it is not.

svg:hover {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: dash 5s linear forwards;
}
@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<svg width="160" height="80">

  <a xlink:href="/next_video" target="_self">
    <rect class="path" height="70" width="130" y="5" x="5" rx="35" stroke="#eee" stroke-width="8px" />
    <rect height="60" width="120" y="10" x="10" rx="30" fill="#00a6bc" />
    <text fill="#eee" text-anchor="middle" y="45" x="70">Next video</text>
  </a>
</svg>


Solution

  • There is no way to change the start position of the dash of a SVG <rect>.

    To achieve what you want, you need to switch to a <path> element and draw its shape yourself. Then you can start the path wherever you wish.

    svg:hover {
      stroke-dasharray: 1000;
      stroke-dashoffset: 1000;
      animation: dash 5s linear forwards;
    }
    @keyframes dash {
      to {
        stroke-dashoffset: 0;
      }
    }
    <svg width="160" height="80">
    
      <a xlink:href="/next_video" target="_self">
        <path d="M70,5 L100,5 A35,35 0 0 1 100,75 L40,75 A35,35 0 0 1 40,5 Z"
              stroke="#eee" stroke-width="8px" />
        <rect height="60" width="120" y="10" x="10" rx="30" fill="#00a6bc" />
        <text fill="#eee" text-anchor="middle" y="45" x="70">Next video</text>
      </a>
    </svg>