web: Support save2png

This commit is contained in:
Jinny You 2024-01-04 16:05:08 +09:00 committed by Hermet Park
parent 958481b0cb
commit d06414400e
2 changed files with 30 additions and 8 deletions

View file

@ -15,6 +15,7 @@
<button onclick="playAnimation()">Play</button>
<button onclick="save2gif()">save2gif</button>
<button onclick="save2tvg()">save2tvg</button>
<button onclick="save2png()">save2png</button>
<div>
<label for="reverseCheckbox">Reverse</label>
<input type="checkbox" id="reverseCheckbox" onchange="toggleReverse(event)">
@ -103,6 +104,10 @@
function save2tvg() {
animation.save('tvg');
}
function save2png() {
animation.save('png');
}
</script>
</body>
</html>

View file

@ -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<void> {
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);
}
/**