How To Implement Image Magnification Using GSAP In Angular

Introduction

We can implement image magnifier fuctionlity with GSAP. GSAP provides various feature to perform awesome animation. Tweens and other timelines are contained by TimelineLite, a potent sequencing tool that makes it easy to control them all at once and precisely regulate their timing.

Let’s make image magnification…

HTML file

<img id="main-img" height="750" src="https://assets.hongkiat.com/uploads/nature-photography/The-best-nature-photography-collection.jpg"/>
<div id="zoom">
<img id="zoom-img" />
</div>

CSS file

#main-img {
  display: block;
  margin: 20px auto;  
  border: 1px solid rgba(255,255,255,0.2);
  filter: grayscale(0);
}

#zoom-img {
  pointer-events: none;
  position: relative;
  top: 50%;
  left: 50%;
}

#zoom {
  position: absolute;
  width: 250px;
  height: 250px;
  box-shadow: 0 0 0 2px rgba(255,0,0,0.5),
    5px 5px 10px 5px rgba(0,0,0,0.2);
  border-radius: 50%;  
  top: 0;
  left: 0;
  overflow: hidden;
  pointer-events: none;
  visibility: hidden;
  opacity: 0;
}

JS file

var zoom    = document.querySelector("#zoom");
var zoomImg = document.querySelector("#zoom-img");
var mainImg = document.querySelector("#main-img");
var enterTL = new TimelineMax({ paused: true });
var timer   = TweenLite.delayedCall(1, () => enterTL.reverse()).pause();

var cx, cy, ratio;

window.addEventListener("load", init);

function init() {
  
  zoomImg.src = mainImg.src;
  ratio = mainImg.naturalWidth / mainImg.width;
  resize();
  
  TweenLite.set([zoom, zoomImg], { xPercent: -50, yPercent: -50 });
  TweenLite.set(zoom, { autoAlpha: 0, scale: 0 });
  
  enterTL
    .to(mainImg, 0.5, { filter: "grayscale(1)", "-webkit-filter": "grayscale(1)" }, 0)
    .to(zoom, 0.5, { autoAlpha: 1, scale: 1.5}, 0)
    
  window.addEventListener("resize", resize);  
  mainImg.addEventListener("mouseleave", leaveAction);
  mainImg.addEventListener("mousemove", moveAction);
}

function leaveAction() {
  enterTL.reverse();
}

function moveAction(e) {
  enterTL.play();
  timer.restart(true);
  TweenLite.set(zoom, { x: e.x, y: e.y });
  TweenLite.set(zoomImg, { x: (cx - e.x) * ratio, y: (cy - e.y) * ratio }); 
}

function resize() { 
  var rect = mainImg.getBoundingClientRect();
  cx = rect.left + rect.width /2  ;
  cy = rect.top  + rect.height /2  ;
}

OUTPUT:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories