cropperjs的高度過大(container height too much) ...
cropperjs的高度過大(container height too much)
標簽(空格分隔): JavaScript
業務需要web頭像裁切,用canvas寫了個demo卡成一匹馬,於是就去尋找現成的,發現了cropperjs這個lib,4k star。
在ionic項目中使用時(不打包app),發現高度總是遠高於圖片顯示高度,查找Issues作者只是說給圖片加最大寬度100%,這裡需要註意,width: 100%的同時還必須給圖片一個父容器,直接在ion-content
下是沒有作用的。
<ion-content>
<input type="file" (change)="selectFile($event)">
<div class="img-contaier">
<img [src]="src" alt="" height="auto" width="100%" #img>
</div>
<img [src]="previewSrc" alt="" #preview>
<button ion-button (click)="imgCropper()">cropper</button>
</ion-content>
import...
declare const Cropper;
@Component...
export class HomePage {
public previewSrc: string;
public cropper: any;
public src: string;
@ViewChild('img') img: ElementRef;
@ViewChild('preview') preview: ElementRef;
constructor(
public navCtrl: NavController
) { }
file2Base64(e) {
const f = e;
return new Promise((resolve, reject) => {
if (f) {
const reader = new FileReader();
reader.onload = (file => function(_e) {
resolve({ result: this.result, file: e});
})(f);
reader.readAsDataURL(f);
return;
}
reject(`Get none files.`);
});
}
selectFile(e) {
const file = e.target.files[0];
if (file) {
this.file2Base64(file).then((data: any) => {
this.src = data.result;
if (this.cropper) this.cropper.destroy();
this.img.nativeElement.onload = e => {
this.cropperInit(e);
}
});
}
}
cropperInit(e) {
console.log(e);
const image = e.target;
this.cropper = new Cropper(image, {
viewMode: 1,
aspectRatio: 1 / 1,
background: false
});
}
imgCropper() {
const str = this.cropper.getCroppedCanvas().toDataURL();
this.previewSrc = str;
}
}