0

How do we get the value of a property of an Animation KeyframeEffect for the current time?

For example, suppose we have the following animation with a naive attempt to get a property's current value, without passing any element to the KeyframeEffect, only wishing to animate a number in memory:

const keyframes = new KeyframeEffect(null, [
    { // from
        someProp: 0,
    },
    { // to
        someProp: 35,
    }
], {duration: 2000, easing: 'ease'})

const anim = new Animation(
    keyframes,
    document.timeline
)

anim.play()

requestAnimationFrame(function loop() {
  console.log('current value of someProp:', keyframes.getComputedTiming().progress * 35)

  if (anim.playState != 'finished') requestAnimationFrame(loop)
}, 100)

The output of current value of someProp is incorrect, as my math does not align with the chosen easing of "ease".

Suppose we are on a ScrollTimeline, or the currentTime of the timeline is modified in arbitrary ways we are not aware of, etc. It would get complicated to attempt to figure the value ourselves using custom math and array handling based on current timing.

Is there a way to get the simply access the current value of a property?


The reason we would want to do this is to see if it would be viable to use Web Animations to animate things like WebGL scenes, or canvas drawings, or anything that does not animate DOM element CSS properties.

trusktr
  • 44,284
  • 53
  • 191
  • 263
  • Could you elaborate on why you say the value output to the console is not correct? It appears correct to me. If I plot those values I get the curve for "ease". You are just reading back the progress value so you don't need to pass any keyframes (`null` will work for the keyframes argument). Unfortunately there is not yet a way to read back the contribution of an individual property in a KeyframeEffect to its target although there is a proposal to expose the property interpolator: https://github.com/w3c/csswg-drafts/issues/2069 – brianskold May 18 '21 at 03:45
  • @brianskold You got what I mean though. I can't get the interpolated value of a property without doing the math myself, which makes this impractical to use with anything other than DOM CSS properties. I want to animate numbers for use in custom WebGL or canvas 2D graphics, or etc (any library that accepts numbers for rendering that isn't directly CSS, even any library that is written on top of CSS). So Tween.js it will be (which is sad, I was hoping the web's API would be more generic, rather than me having to add duplicate code to my app besides the native code). – trusktr May 23 '21 at 04:12

0 Answers0