|
| 1 | +using Microsoft.AspNetCore.Components; |
| 2 | +using Microsoft.JSInterop; |
| 3 | + |
| 4 | +namespace TomAndJerry.Component; |
| 5 | + |
| 6 | +public partial class LottieAnimation : IDisposable |
| 7 | +{ |
| 8 | + [Parameter] public string AnimationPath { get; set; } = ""; |
| 9 | + [Parameter] public string Width { get; set; } = "300px"; |
| 10 | + [Parameter] public string Height { get; set; } = "300px"; |
| 11 | + [Parameter] public bool Loop { get; set; } = true; |
| 12 | + [Parameter] public bool Autoplay { get; set; } = true; |
| 13 | + [Parameter] public string Renderer { get; set; } = "svg"; |
| 14 | + [Parameter] public string AdditionalStyles { get; set; } = ""; |
| 15 | + [Parameter] public string CssClass { get; set; } = ""; |
| 16 | + |
| 17 | + private string ContainerId { get; set; } = ""; |
| 18 | + private IJSObjectReference? lottieModule; |
| 19 | + |
| 20 | + protected override async Task OnAfterRenderAsync(bool firstRender) |
| 21 | + { |
| 22 | + if (firstRender && !string.IsNullOrEmpty(AnimationPath)) |
| 23 | + { |
| 24 | + ContainerId = $"lottie-container-{Guid.NewGuid():N}"; |
| 25 | + await LoadLottieAnimation(); |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + private async Task LoadLottieAnimation() |
| 30 | + { |
| 31 | + try |
| 32 | + { |
| 33 | + lottieModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./js/lottie-interop.js"); |
| 34 | + await lottieModule.InvokeVoidAsync("loadLottieAnimation", new |
| 35 | + { |
| 36 | + containerId = ContainerId, |
| 37 | + path = AnimationPath, |
| 38 | + renderer = Renderer, |
| 39 | + loop = Loop, |
| 40 | + autoplay = Autoplay |
| 41 | + }); |
| 42 | + } |
| 43 | + catch (Exception ex) |
| 44 | + { |
| 45 | + Console.WriteLine($"Error loading Lottie animation: {ex.Message}"); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + public async Task Play() |
| 50 | + { |
| 51 | + if (lottieModule != null) |
| 52 | + { |
| 53 | + await lottieModule.InvokeVoidAsync("playAnimation", ContainerId); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public async Task Pause() |
| 58 | + { |
| 59 | + if (lottieModule != null) |
| 60 | + { |
| 61 | + await lottieModule.InvokeVoidAsync("pauseAnimation", ContainerId); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + public async Task Stop() |
| 66 | + { |
| 67 | + if (lottieModule != null) |
| 68 | + { |
| 69 | + await lottieModule.InvokeVoidAsync("stopAnimation", ContainerId); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public async Task SetSpeed(float speed) |
| 74 | + { |
| 75 | + if (lottieModule != null) |
| 76 | + { |
| 77 | + await lottieModule.InvokeVoidAsync("setAnimationSpeed", ContainerId, speed); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + public void Dispose() |
| 82 | + { |
| 83 | + lottieModule?.DisposeAsync(); |
| 84 | + } |
| 85 | +} |
0 commit comments