简体   繁体   中英

Animate svg rect on button click

I want to animate the width of a svg rect.

Initially, rect width should be 0, on button click the width should grow in 5 seconds to 100% of the width.

I create this codesandbox .

I basically create this class:

.grow {
  animation: growAnimation 5s linear 1;
}

@keyframes growAnimation {
  from {
    transform: scale(0%, 100%);
  }
  to {
    transform: scale(100%, 100%);
  }
}

I assign this class only when user clicks on button but it doesn't work: rect width is 0 and on click is 100%, there is no growing during 5 seconds. Why?

Is there a better way to to this? In the future I have to do also a press and hold animation:

  • on button click the animation start
  • on button hold the animation continue
  • if user releases the button before the growing animation ends, then there is the inverse animation (from 100% to 0%).

you should pass parameters to scale property as number not as percentage:

@keyframes growAnimation {
  from {
    transform: scale(0, 1);
  }
  to {
    transform: scale(1, 1);
  }
}

See this Working Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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