[JS]무한반복해서 흐르는 텍스트 애니메이션

전유덕·2024년 1월 10일
0
post-thumbnail

개요

과제물에 해당효과를 사용하기 위해 작성합니다.
코드리뷰는 어려워서 못하겠고.. 일단은 그냥 사용해야겠습니다.

코드

Html

<section class="hero-section">
  <div class="loop-container">
    <div class="item">Infinite Horizontal Looping Text&nbsp;</div>
    <div class="item">Infinite Horizontal Looping Text&nbsp;</div>
  </div>
</section>

CSS

body { min-height: 400vh;  /* force some scrollbars */ }

.hero-section {
  position: relative;
  top: 50vh;
  overflow: hidden;
  font: 900 9vw/1 sans-serif;
  min-height: 100vh;
}

JS

function createLoopingText(el) {
  const lerp = (current, target, factor) => current * (1 - factor) + target * factor;

  const state = {
    el, 
    lerp: {
      current: 0,
      target: 0 
    },
    interpolationFactor: 0.1,
    speed: 0.2, 
    direction: -1
  };
  
  state.el.style.cssText = 'position: relative; display: inline-flex; white-space: nowrap;';
  state.el.children[1].style.cssText = `position: absolute; left: ${100 * -state.direction}%;`;

  
  function animate() {
    state.lerp.target += state.speed;
    state.lerp.current = lerp(state.lerp.current, state.lerp.target, state.interpolationFactor);

    if (state.lerp.target > 100) {
      state.lerp.current -= state.lerp.target;
      state.lerp.target = 0;
    }

    const x = state.lerp.current * state.direction;
    state.el.style.transform = `translateX(${x}%)`;
  }

  function render() {
    animate();
    window.requestAnimationFrame(render);
  }

  render();
  return state;
}

document.querySelectorAll('.loop-container').forEach(el => createLoopingText(el));

결과

profile
zi존 개발자 되고싶다ㅏㅏ(훈수 대환영!)

0개의 댓글