티스토리 뷰

HTML&CSS

Lottie 라이브러리 활용 예시

beecomci 2018. 10. 25. 17:58

모웹 마크업에 Lottie 애니메이션 라이브러리를 사용하게 되면서 알게된 점들을 정리해보았다.

개요

After Effects 애니메이션을 실시간을 렌더링 하는 iOS, android, react-native, web 라이브러리이며,
Bodymovin 이라는 오픈소스를 이용한 After Effects 확장 기능을 사용해서 json 형식으로 추출한 애니메이션 데이터를 사용하여 웹상에서 애니메이션을 렌더링한다.


장점

  • 리소스 절감
    • gif 애니메이션보다 훨씬 작은 용량으로 제작되어 리소스를 대폭 줄일 수 있다.
    • gif는 용량이 클 뿐만 아니라 고정된 크기로 렌더링 되기 때문에 해상도 대응이 어렵다. 하지만 json 데이터 파일로 제작하면 해상도에 제한이 없다는 장점이 있다.
  • 편리함
    • 기존에는 디자이너가 원하는 모션을 구현하기 위해서 디자이너에게 모든 수치를 받아서 애니메이션을 구현해야 했다. 하지만 Lottie를 사용함으로써 디자이너에게 json 파일을 받아 바로 개발에 적용시키기만 하면 되는 편리함이 생긴다.
  • Keyframes vs Lottie
    • Keyframes는 2016년 11월에 Facebook에서 만든 애니메이션 라이브러리이다.

      (Facebook 모바일 화면에서 보이는 여러가지 '좋아요' 애니메이션을 구현시 사용됨)

    • Lottie와 동일하게 After Effects로 애니메이션을 만들고 json 형식으로 추출하여 android, iOS, web에서 읽어 애니메이션을 렌더링할 수 있다.

    • Keyframes는 적은 용량의 애니메이션을 구현하려는 목적에 맞게 만들다 보니 스펙이 제한적인 반면, Lottie는 실제 After Effects에서 사용하는 다양한 효과들을 대부분 지원한다.

단점

코드 차원의 문제라기 보다는 현재, Bodymovin에서 json 파일로 추출할 수 있는 After Effects 플러그인의 한계가 있다. 관련한 여러가지 이슈들이 등록되었으며 버전업을 통해 차차 개선중이다.
이슈 : https://github.com/airbnb/lottie-web/issues





사용방법

1. 폴더 구조


2. index.html
https://cdnjs.com/libraries/bodymovin 에서 bodymovin.js 를 cdn으로 받아온다.

...
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/4.13.0/bodymovin.js"></script>
...

애니메이션이 불러질 영역 생성

<span id="lottie"></span>

3. common.js

var animation = bodymovin.loadAnimation({
  container: document.getElementById('lottie'), // Required
  path: 'data.json', // Required
  renderer: 'svg', // Required
  loop: true, // Optional
  autoplay: true // Optional
});



예제

참고 url : https://codepen.io/dbwls94/project/editor/DVapKz

1. 기본

common.js

var animation1 = bodymovin.loadAnimation({
  container: document.getElementById('lottie1'),
  renderer: 'svg',
  loop: true,
  autoplay: true,
  path: 'loading.json'
});

loop 속성값을 true로 지정하면 애니메이션을 반복하고, autoplay 속성값을 true로 지정하면 자동으로 재생한다.


2. 체크박스

index.html

<h2>Lottie 예제2(체크박스)</h2>
<span class="chk_wrap">
  <input type="checkbox" id="chk1"/>
  <label for="chk1" class="lottie2"></label>
</span>
<span class="chk_wrap">
  <input type="checkbox" id="chk2"/>
  <label for="chk2" class="lottie2"></label>
</span>
<span class="chk_wrap">
  <input type="checkbox" id="chk3"/>
  <label for="chk3" class="lottie2"></label>
</span>

<input type="checkbox"/> 에 애니메이션이 직접 적용되지 않아서, label 태그로 대체해서 사용했다.


common.js

var btnList = document.getElementsByClassName("lottie2");
for (var i = 0, l = btnList.length; i < l; i++) {
  (function(n) {
   var animation2 = bodymovin.loadAnimation({
    container : btnList[n],
    render: "svg",
    loop: false,
    autoplay: false,
    path: "check.json"
   });

   $(btnList[n]).on("click", function() {
    if ($(this).hasClass('on')) {
      animation2.stop();
      $(this).removeClass('on');
    } else {
      animation2.play();
      $(this).addClass('on');
    }
   });
  })(i);
}

체크박스를 클릭할 때마다 'on' 클래스명을 추가하여 애니메이션이 동작/정지되도록 했다.


3. 애니메이션 일시정지(pause)
1개의 json 파일로 애니메이션을 프레임 단위로 쪼개서 사용할 수 있으며,
1개의 요소에 2가지 이상 종류의 애니메이션을 적용해야 할 경우에 유용하게 사용할 수 있다.
(아래 예제의 파일은 정지→재생, 재생→정지 애니메이션 2가지가 합쳐진 json 파일)

      

(json 파일을 그냥 실행시켰을 때)(프레임 단위로 정지/재생 2개 단위로 쪼갰을 때 - 클릭 이벤트)


디자이너에게 전달받은 가이드 예시


index.html

<h2>Lottie 예제3(pause animation)</h2>
<button type="button" id="play_stop" class="off"><span class="blind">중지</span></button>

common.js

var animation3 = bodymovin.loadAnimation({
    container: document.getElementById('play_stop'),
    renderer: 'svg',
    loop: false,
    autoplay: false,
    path: 'music.json'
});

animation3.addEventListener('DOMLoaded',function(){
  if($('#play_stop').hasClass('off')) {
    animation3.goToAndStop(23, true);
  }
  else if($('#play_stop').hasClass('on')) {
    animation3.goToAndStop(1, true);      
  }

});

$(document).on('click','#play_stop',function(){
  if($(this).hasClass('off')) {
    //off -> on
    animation3.playSegments([23,42], true);
    $('.blind').text('재생');
    $(this).removeClass('off');
    $(this).addClass('on');
  }
  else if($(this).hasClass('on')) {
    //on -> off
    animation3.playSegments([1,23], true);
    $('.blind').text('중지');
    $(this).removeClass('on');
    $(this).addClass('off');
  }
});

※ 참고

goToAndStop(value, isFrame)

  • value : numeric value.
  • isFrame : defines if first argument is a time based value or a frame based (default false).

goToAndStop 메소드의 첫번째 인자는 제어할 프레임을 넘기고, 두번째 인자는 첫번째 인자가 시간 기반인지 프레임 기반인지를 boolean값으로 넘겨준다.


playSegments(segments, forceFlag)

  • segments : array. Can contain 2 numeric values that will be used as first and last frame of the animation. Or can contain a sequence of arrays each with 2 numeric values.
  • forceFlag : boolean. If set to false, it will wait until the current segment is complete. If true, it will update values immediately.

playSegments 메소드의 첫번째 인자는 제어할 시작 프레임과 종료 프레임을 배열로 넘기고, 두번째 인자로는 제어할 부분을 바로 실행시키기 위한 boolean값을 넘겨준다.


4. 라인웹툰 인앱 웹뷰 예시



'HTML&CSS' 카테고리의 다른 글

벤더 프리픽스(vendor prefix)  (0) 2019.06.10
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함