fand / vfx-js

WebGL effects made easy.
https://amagi.dev/vfx-js
640 stars 20 forks source link

Is there a way to avoid having animations when they exit the viewport? #93

Closed fredm00n closed 1 month ago

fredm00n commented 1 month ago

I've checked the documentation and I love how transitions work when an element ENTERS the viewport.

However, is there a way to avoid having these animations repeat every time the elements exit (then re-enter) the viewport?

Many thanks!

fand commented 1 month ago

Hi @fredmoon! Currently VFX-JS doesn't have the onetime transition option... When I implemented intersection options I had an idea to add once: boolean; flag to do that, but I dropped that feature thinking it might be an overkill😅

However, you can make onetime transitions using custom uniforms, for example:

let hasEntered = false;
let enteredAt = Infinite;

vfx.add(el, {  shader, uniforms: {  
  enterTime2: () => {
    // Check intersection
    if (!hasEntered) {
      const r = el.getBoundingClientRect();     
      const isVisible = r.right >= 0 && r.left <= window.innerWidth && r.top <= window.innerHeight && r.bottom >= 0;
      if (isVisible) {
        hasEntered = true;
        enteredAt = Date.now() / 1000;
      }
    }

    return Math.max(Date.now() / 1000 - enteredAt, 0);
  } 
} });

Tweaking the shader:

uniform float enterTime2;
void main() {
  gl_FragColor = texture(src, uv) * clamp(enterTime, 0., 1.); // fade effect
}
fredm00n commented 1 month ago

Thank you so much again. This is incredibly helpful!