Skip to content

Instantly share code, notes, and snippets.

@Indrajitsaha1997
Created March 28, 2023 09:40
Show Gist options
  • Save Indrajitsaha1997/3eae1ee18cdafef4324cd36c0a6d70ab to your computer and use it in GitHub Desktop.
Save Indrajitsaha1997/3eae1ee18cdafef4324cd36c0a6d70ab to your computer and use it in GitHub Desktop.
Lottie in HTML (On click)

Use Lottie In HTML

First you have to add Bodymovin. Bodymovin is a free extension that lets you export After Effects compositions as JSON files to embed in websites and add to apps.

npm install lottie-web

And then, in your HTML file, include the script from the dist folder in the installed package. You could also import the library as a module from Skypack

import lottieWeb from 'https://cdn.skypack.dev/lottie-web';

N.B. : If you are getting the following error,

"Uncaught SyntaxError: Cannot use import statement outside a module"

Please add the following code in <script> tag

<script type="module">

Animating on a trigger

The goToAndStop(value, isFrame) method is appropriate here. When the animation has loaded in the container, this method sets the animation to go to the provided value, then stop there. In this situation, we’d have to find the animation value when it’s at play and set it. The second parameter specifies whether the value provided is based on time or frame. It’s a boolean type and the default is false (i.e., time-based value). Since we want to set the animation to the play frame, we set it to true.

Here's the code as an example

<!DOCTYPE  html>
	<html  lang="en">
	<head>
	<meta  charset="UTF-8">
	<meta  http-equiv="X-UA-Compatible"  content="IE=edge">
	<meta  name="viewport"  content="width=device-width, initial-scale=1.0">
	<title>POC-Use Lottie in web</title>
	
	<script  type="module">
	import  lottieWeb  from  'https://cdn.skypack.dev/lottie-web';
	var  container = document.getElementById('container');
	var  state = 'play';
	
	var  animation = lottieWeb.loadAnimation({
	container:  container,
	path:  'https://assets10.lottiefiles.com/packages/lf20_wMezg6.json',
	renderer:  'svg',
	loop:  false,
	autoplay:  false,
	name:  "Demo Animation",
	});
	
	animation.goToAndStop(100, true);
	
	container.addEventListener('click', () => {
		if (state === 'play') {
		animation.playSegments([0, 100], true);
		state = 'pause';
		} else {
		animation.playSegments([0, 100], true);
		state = 'play';
		}
	});

	</script>
	</head>
	<body>
		<button  id="container"  style="width: 99vw;height: 98vh;cursor: pointer;"></button>
	</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment