definma-ui/src/app/img-magnifier/img-magnifier.component.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-07-14 15:58:33 +02:00
import {AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-img-magnifier',
templateUrl: './img-magnifier.component.html',
styleUrls: ['./img-magnifier.component.scss']
})
export class ImgMagnifierComponent implements OnInit, AfterViewInit {
2020-09-03 15:51:53 +02:00
@Input() src: string; // image source
@Input() zoom: number; // zoom level
@Input() magnifierSize: {width: number, height: number}; // size of the magnifier
2020-07-14 15:58:33 +02:00
@ViewChild('mainImg') mainImg: ElementRef;
backgroundSize;
2020-09-03 15:51:53 +02:00
magnifierPos = {x: 0, y: 0}; // position of the magnifier
2020-07-14 15:58:33 +02:00
showMagnifier = false;
constructor(
private window: Window
) { }
ngOnInit(): void {
}
ngAfterViewInit() {
setTimeout(() => {
this.calcBackgroundSize();
}, 1);
}
2020-09-03 15:51:53 +02:00
calcPos(event) { // calculate the current magnifier position
2020-07-14 15:58:33 +02:00
const img = this.mainImg.nativeElement.getBoundingClientRect();
2020-08-12 11:06:46 +02:00
this.magnifierPos.x = Math.min(
img.width - this.magnifierSize.width,
Math.max(0, event.pageX - img.left - this.window.pageXOffset - this.magnifierSize.width / 2)
);
this.magnifierPos.y = Math.min(
img.height - this.magnifierSize.height + 7,
Math.max(0, event.pageY - img.top - this.window.pageYOffset - this.magnifierSize.height / 2)
);
2020-07-14 15:58:33 +02:00
}
calcBackgroundSize() {
2020-09-03 15:51:53 +02:00
this.backgroundSize = this.mainImg ? (this.mainImg.nativeElement.width * this.zoom - this.magnifierSize.width) +
'px ' + (this.mainImg.nativeElement.height * this.zoom - this.magnifierSize.height) + 'px ' : '0 0';
2020-07-14 15:58:33 +02:00
}
}