import { Component, OnInit, ViewEncapsulation, ElementRef, ViewChild, Input, EventEmitter, Output, OnDestroy } from '@angular/core';
import Cropper from 'cropperjs';
export interface ImageCropperSetting {
width: number;
height: number;
}
@Component({
selector: 'app-picture-croper',
templateUrl: './picture-croper.component.html',
styleUrls: ['./picture-croper.component.less'],
encapsulation: ViewEncapsulation.None
})
export class PictureCroperComponent implements OnInit, OnDestroy {
@ViewChild('image') image: ElementRef;
@Input() imageUrl: string;
@Input() loadImageErrorText: string;
@Input() cropperOptions: any = {};
@Input() aspectRatio: number;
@Input() loading = false;
@Output() cropperReady = new EventEmitter();
@Output() cropperError = new EventEmitter();
public cropper: Cropper;
public imageElement: HTMLImageElement;
public loadError = false;
constructor() {
this.loadImageErrorText = '图片加载失败,请检查URL是否正确。';
}
ngOnInit() {
}
/**
* Image loaded
*/
imageLoaded(ev: Event) {
// Unset load error state
this.loadError = false;
this.loading = true;
// Setup image element
const image = ev.target as HTMLImageElement;
this.imageElement = image;
// Add crossOrigin?
image.crossOrigin = 'anonymous';
// Set crop options
// extend default with custom config
this.cropperOptions = Object.assign(this.cropperOptions, {
aspectRatio: this.aspectRatio,
movable: false,
scalable: false,
zoomable: false,
viewMode: 1,
checkCrossOrigin: true,
checkOrientation: false,
ready: () => {
// Emit ready
this.cropperReady.emit(true);
this.loading = false;
}
});
// Set cropperjs
if (this.cropper) {
this.cropper.destroy();
this.cropper = undefined;
}
this.cropper = new Cropper(image, this.cropperOptions);
}
/**
* Image load error
*/
imageLoadError() {
// Set load error state
this.loadError = true;
// emit error
this.cropperError.emit(true);
}
ngOnDestroy() {
if (this.cropper) {
this.cropper.destroy();
this.cropper = undefined;
}
}
}