Mr No
Mr No

Reputation: 143

JavaScript animate key frames by percentage

I am trying to animate an object tipping, then being set right. My JavaScript looks like this:

function animate-tip(){
  document.getElementById("x").animate(
  [0% { transform: "rotate(0deg)"},
   30% { transform: "rotate(30deg)"},
   100% { transform: "rotate(0deg)"}],
   {
     duration: 500,
     iterations: 1
   })

Obviously this is incorrect syntax. How can I make this animation work by percentages?

Upvotes: 1

Views: 2028

Answers (1)

Richard Hunter
Richard Hunter

Reputation: 2180

You do it with the offset property. It must be between 0 and 1, so just convert your percentages by dividing by 100.

function animateTip() {
  document.getElementById("x").animate(
    [{
        transform: "rotate(0deg)"
      },
      {
        transform: "rotate(30deg)", offset: 0.3,
      },
      {
        transform: "rotate(0deg)"
      }
    ], {
      duration: 3500,
      iterations: 1
    })
}

animateTip();
#x {
  padding: 10px;
  background: chartreuse;
  display: inline-block;
  width: 100px;
  height: 100px;
}
<div id="x"></div>

Upvotes: 8

Related Questions