diff --git a/web/example/index.html b/web/example/index.html index f303dcec..75b9a855 100644 --- a/web/example/index.html +++ b/web/example/index.html @@ -15,6 +15,7 @@ +
@@ -103,6 +104,10 @@ function save2tvg() { animation.save('tvg'); } + + function save2png() { + animation.save('png'); + } \ No newline at end of file diff --git a/web/src/lottie-player.ts b/web/src/lottie-player.ts index 57e6528a..0c4fe727 100644 --- a/web/src/lottie-player.ts +++ b/web/src/lottie-player.ts @@ -46,6 +46,7 @@ export interface LibraryVersion { export enum ExportableType { GIF = 'gif', TVG = 'tvg', + PNG = 'png', } // Define mime type which player can load @@ -166,6 +167,15 @@ const _observerCallback = (entries: IntersectionObserverEntry[]) => { } } +const _downloadFile = (fileName: string, blob: Blob) => { + const link = document.createElement("a"); + link.setAttribute('href', URL.createObjectURL(blob)); + link.setAttribute('download', fileName); + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); +} + @customElement('lottie-player') export class LottiePlayer extends LitElement { /** @@ -595,7 +605,20 @@ export class LottiePlayer extends LitElement { * @since 1.0 */ public async save(target: ExportableType): Promise { - if (!this._TVG || !this.src) { + if (!this._TVG) { + return; + } + + const fileName = `output.${target}`; + + if (target === ExportableType.PNG) { + this._canvas!.toBlob((blob: Blob | null) => { + if (!blob) { + return; + } + + _downloadFile('output.png', blob); + }, 'image/png'); return; } @@ -604,7 +627,6 @@ export class LottiePlayer extends LitElement { throw new Error('Unable to save. Error: ', this._TVG.error()); } - const fileName = `output.${target}`; const data = _module.FS.readFile(fileName); if (target === ExportableType.GIF && data.length < 6) { @@ -620,12 +642,7 @@ export class LottiePlayer extends LitElement { } const blob = new Blob([data], {type: 'application/octet-stream'}); - const link = document.createElement("a"); - link.setAttribute('href', URL.createObjectURL(blob)); - link.setAttribute('download', fileName); - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); + _downloadFile(fileName, blob); } /**