简体   繁体   中英

How to render Vanilla JS animation in Angular

I have to apply some animation to my error page component in angular. I have already designed an animated page using Vanilla JS. Now I need to apply those logics of animation in the script tag to my angular component. How to achieve this? Please help me. My code goes here:

<div id="container">
    <div class="content">
        <h2>404</h2>
        <h4>Opps! Page not found</h4>
        <p>
            The page you were looking for doesn't exist. You may
            have mistyped the address or the page may have moved.
        </p>
        <a href="#">Back To Home</a>
    </div>
</div>
<script type="text/javascript">
    var container = document.getElementById('container');
    window.onmousemove = function(e){
        var x = - e.clientX/5,
            y = - e.clientY/5;
        container.style.backgroundPositionX = x + 'px';
        container.style.backgroundPositionY = y + 'px';
    }
</script>

if the target element is in the component template

<div class="container" (mousemove)="onMousemoveHandler($event)">
</div>

componnet

  onMousemoveHandler(e: MouseEvent) {

    const x = -e.clientX / 5;
    const y = -e.clientY / 5;

    const container = e.target as HTMLElement;
    container.style.backgroundPositionX = x + "px";
    container.style.backgroundPositionY = y + "px";
  }

demo

while the preview answer is working fine but in case you want to use the same effect on other element not inside this component angular directive is the perfect use case here.

BgTiltDirective

@Directive({
  selector: "[bgTilt]"
})
export class BgTiltDirective {
  @HostListener("mousemove", ["$event", "$event.target"]) handler(
    e: MouseEvent,
    elm: HTMLElement
  ) {
    const x = -e.clientX / 5;
    const y = -e.clientY / 5;

    elm.style.backgroundPositionX = x + "px";
    elm.style.backgroundPositionY = y + "px";
  }
}

template

<div class="container" bgTilt></div>

demo ♂️

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM