panzoom
panzoom copied to clipboard
clicking on Zoom In and Zoom out buttons doesnt zoom from center of image
Hi , I am trying to add zoomIn and zoomOut button to my application. I was able to zoom from center with mouse pinch, but the same with button is not working.
Please find the related code:
component.html
<ng-container>
<img id="image" #image [src]="imgData">
<div class="zoomBtn">
<button class="zoomOut" (click)="zoomToggle(true)">
<img src="../assets/images/zoom_in.svg" >
</button>
<button class="zoomIn" (click)="zoomToggle(false)">
<img src="../assets/images/zoom_out.svg" >
</button>
</div>
</ng-container>
component.ts
import {
Component,
EventEmitter,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
AfterViewInit, ElementRef, ViewChild
} from "@angular/core";
import panzoom from "panzoom";
declare var _paq: any;
@Component({
selector: "app-text-image-rend",
templateUrl: "./text-image-rend.component.html",
styleUrls: ["./text-image-rend.component.scss"]
})
export class TextImageRendComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@ViewChild('image', { static: false }) image: ElementRef;
panZoomController;
panzoom;
zoomLevels: number[];
currentZoomLevel: number;
constructor() {}
ngOnInit() {
this.displayTemplateData();
}
ngOnChanges() {
if(this.panZoomController){
this.panZoomController.moveTo(0, 0);
this.panZoomController.zoomAbs(0, 0, 1);
}
const element = document.getElementById("data");
element.scrollTop = 0;
this.currentTab = 0;
this.displayTemplateData();
}
ngAfterViewInit() {
this.zoomLevels = [0.1, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3];
this.currentZoomLevel = this.zoomLevels[4];
this.panZoomController = panzoom(this.image.nativeElement,{transformOrigin: {x: 0.5, y: 0.5}});
}
displayTemplateData() {
this.imgData = this.dom.bypassSecurityTrustUrl(
"data:" + this.templateData.mimetype + ";base64," + this.templateData.data
);
}
zoom() {
const isSmooth = false;
const scale = this.currentZoomLevel;
if (scale) {
const transform = this.panZoomController.getTransform();
const deltaX = transform.x;
const deltaY = transform.y;
const offsetX = scale + deltaX;
const offsetY = scale + deltaY;
if (isSmooth) {
this.panZoomController.smoothZoom(0, 0, scale);
} else {
this.panZoomController.zoomAbs(offsetX, offsetY, scale);
}
}
}
zoomToggle(zoomIn: boolean) {
const idx = this.zoomLevels.indexOf(this.currentZoomLevel);
if (zoomIn) {
if (typeof this.zoomLevels[idx + 1] !== 'undefined') {
this.currentZoomLevel = this.zoomLevels[idx + 1];
}
} else {
if (typeof this.zoomLevels[idx - 1] !== 'undefined') {
this.currentZoomLevel = this.zoomLevels[idx - 1];
}
}
if (this.currentZoomLevel === 1) {
this.panZoomController.moveTo(0, 0);
this.panZoomController.zoomAbs(0, 0, 1);
} else {
this.zoom();
}
}
}
Hi I am getting Cannot read property 'nativeElement' of undefined at OperationalDashboardComponent.ngAfterViewInit.
Please, help me how to fix it.