Search code examples
csssvgcss-animationssvg-animate

SVG animation not working as expected


I am working on SVG animation where I want to draw a rectangle using svg stroke animation. Here is my code.

.path {
  stroke-dasharray: 1400;
  stroke-dashoffset: 100;
  animation: dash 5s linear infinite;
}

@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
	 width="500px" height="500px" viewBox="100 300 500 600" enable-background="new 0 0 340 333" xml:space="preserve"><path id="XMLID_348_" class="st0 laptop-outer path" d="M523.9,704.5H119.3c-9.1,0-16.5-7.1-16.5-15.8V449.5c0-14.1,12-25.6,26.8-25.6h384.2     c14.8,0,26.8,11.5,26.8,25.6v239.1C540.5,697.4,533.1,704.5,523.9,704.5z M129.5,425.5c-13.9,0-25.2,10.8-25.2,24.1v239.1 c0,7.9,6.7,14.3,15,14.3h404.6c8.2,0,15-6.4,15-14.3V449.5c0-13.3-11.3-24.1-25.2-24.1H129.5z" stroke="#000000" stroke-width="4" /></svg>

I want to draw a rectangle from one point to the last point but it's not working as I expected.


Solution

  • You may consider an easier path for your SVG:

    path {
      fill: transparent;
      stroke: #000;
      stroke-dasharray: 212;
      stroke-dashoffset: 212;
      animation: dash 5s linear forwards;
    }
    
    @keyframes dash {
      to {
        stroke-dashoffset: 0;
      }
    }
    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' width='200'>
      <path stroke-width=0.5 d='M0 16 L0 32 C0 48 0 48 16 48 L48 48 C64 48 64 48 64 32 L64 16 C64 0 64 0 48 0 L16 0 C0 0 0 0 0 16 Z' />
    </svg>