'Temporary animation over image after clicking it (Angular 13)
I'm working on an Angular 13 application with a quite simple combat system, in which you can attack enemies by clicking their images, and I'm looking a way to achieve a "hit effect" to represent damage whenever you click on their images. Something like turning the image to red for one second, with a CSS rule like this one:
filter: grayscale(100%) brightness(35%) sepia(100%) hue-rotate(-50deg) saturate(534%) contrast(1.3);
I don't know if this can be done with Angular animations, or maybe just by CSS animations applying a rule on (click) function that is called after clicking on the image, or even with some kind of hidden overlay which could show up for X seconds somehow with a setTimeout()
call. So, I would appreciate any help on how to achieve something like this in a clean and elegant way. Thank you so much for your time! :)
Solution 1:[1]
Sure, we could animate it back and forth using setTimeout
. I would prefer Angular animations if you want more control how, when or why animation is triggered. Css option is always there of course - a class could be applied with NgClass
.
Html
<div style="display:flex; flex-direction: column">
<ng-container *ngFor="let item of items; let i = index">
<div (click)="isHit(item)" [@removeImage]="item.show">
<img [src]="item.href" />
</div>
</ng-container>
</div>
Ts
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [
// the animation
trigger('removeImage', [
state(
'true',
style({
filter: 'hue-rotate(-50deg)',
})
),
transition('false<=>true', [animate('0.3s 0.0s ease-in')]),
]),
],
})
export class AppComponent {
name = 'Angular';
items = [
{
name: 'A',
show: true,
href: 'https://images-na.ssl-images-amazon.com/images/I/91-Db4L6xjL.png',
},
{
name: 'B',
show: true,
href: 'https://tailandfur.com/wp-content/uploads/2014/03/Funny-pictures-of-animals-41.jpg',
}
];
isHit(item: any) {
item.show = !item.show;
setTimeout(() => {
item.show = !item.show;
}, 300);
}
}
Working example: https://stackblitz.com/edit/angular-animation-when-removing-clts3h?file=src%2Fapp%2Fapp.component.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joosep Parts |