Skip to content

Instantly share code, notes, and snippets.

@justinfagnani
Created June 6, 2019 18:19
Show Gist options
  • Save justinfagnani/49b830898ec2247a6bd609cdbb5ce1c5 to your computer and use it in GitHub Desktop.
Save justinfagnani/49b830898ec2247a6bd609cdbb5ce1c5 to your computer and use it in GitHub Desktop.
<lottie-player>
import lottie from './lib/lottie-import.js';
export class LottiePlayerElement extends HTMLElement {
get src(): string | null {
return this.getAttribute('src');
}
set src(v: string | null) {
if (v == null) {
this.removeAttribute('src');
} else {
this.setAttribute('src', v);
}
}
get loop(): boolean {
return this.hasAttribute('loop');
}
set loop(v: boolean) {
if (v === true) {
this.setAttribute('loop', '');
} else {
this.removeAttribute('loop');
}
}
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot!.innerHTML = `
<style>
:host {
display: block;
width: 100%;
height: 100%;
}
div {
width: 100%;
height: 100%;
}
</style>
<div></div>
`;
}
connectedCallback() {
this._load();
}
private _load() {
lottie.loadAnimation({
wrapper: this.shadowRoot!.querySelector('div'),
animType: 'html',
loop: this.loop,
prerender: true,
autoplay: true,
path: this.src,
});
}
attributeChangedCallback(name: string, _oldValue: string, _newValue: string) {
if (name === 'src' || name === 'loop') {
this._load();
}
}
}
customElements.define('lottie-player', LottiePlayerElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment