Add Zoom In – Out Functionality In Angular

zoom in – out is simply use for reading text and image easily or seeing finer details.

Step: 1

In app.component.html

<h4 class="text-center">Image Zoom In - Out in angular</h4>
<div style="width: 450px; height: 400px; overflow : hidden;  position: relative;margin: 0 auto;" #container>
    <img src="https://picsum.photos/1600/900/?random?4" (click)="onClick($event)" (mousedown)="onMouseDown($event)" (mousemove)="mouseMoveHandler($event)" #img style="cursor : zoom-in; width:100%; transition: all .3s; position: absolute " />
</div>

Step: 2

In app.component.ts

import { Component, ElementRef, OnInit, VERSION, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  isZoomed = false;
  pos = { top: 0, left: 0, x: 0, y: 0 };

  @ViewChild('container') 'container': ElementRef;
  @ViewChild('img') 'img': ElementRef;

  onClick(event:any) {
    this.isZoomed = !this.isZoomed;
    if (this.isZoomed) {
      this.container.nativeElement.style.overflow = 'hidden';
      this.img.nativeElement.style.width = '200%';
      this.img.nativeElement.style.cursor = 'zoom-out';
      this.img.nativeElement.style.cursor = 'zoom-out';
      this.img.nativeElement.style.left = `-${event.clientX}`;
      this.img.nativeElement.style.top = `-${event.clientY}`;
    } else {
      this.container.nativeElement.style.overflow = 'hidden';
      this.img.nativeElement.style.width = '100%';
      this.img.nativeElement.style.cursor = 'zoom-in';
    }
  }
  onMouseDown(event:any) {
    this.pos = {
      // The current scroll
      left: this.container.nativeElement.scrollLeft,
      top: this.container.nativeElement.scrollTop,
      // Get the current mouse position
      x: event.clientX,
      y: event.clientY,
    };
  }

  mouseMoveHandler(event:any) {
    // How far the mouse has been moved
    const dx = (event.clientX - this.pos.x) * 2;
    const dy = (event.clientY - this.pos.y) * 3;

    // Scroll the element
    this.container.nativeElement.scrollTop = this.pos.top - dy;
    this.container.nativeElement.scrollLeft = this.pos.left - dx;
  }

  onLeave() {
    this.container.nativeElement.style.overflow = 'hidden';
    this.img.nativeElement.style.transform = 'scale(1)';
    this.img.nativeElement.style.cursor = 'zoom-in';
  }
}

Step: 3

npm start

output :

Submit a Comment

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

Subscribe

Select Categories