I am using cropper.js (https://github.com/fengyuanchen/cropperjs) to manipulate images, but I could not find a way to crop my image programmatically.
What I am trying to do is create a cropped preview immediately after initialising the cropper.
var cropper = new Cropper(document.getElementById('img'), {
autoCrop: true,
autoCropArea: 1,
aspectRatio: 500 / 660,
minCropBoxWidth: 500,
minCropBoxHeight: 660,
viewMode: 2
});
I have autoCrop
enabled, but if I try to get the data with cropper.getCroppedCanvas()
it returns null
.
I noticed that cropper.cropped
is false, so probably I need to trigger the initial cropping, but no idea how.
I realised that I was trying to generate the preview image too early.
the problem was that the cropper
was not fully initialised yet.
Calling the logic when ready
is fired fixed it:
var cropper = new Cropper(document.getElementById('img'), {
autoCrop: true,
autoCropArea: 1,
aspectRatio: 500 / 660,
minCropBoxWidth: 500,
minCropBoxHeight: 660,
viewMode: 2,
ready: function() {
generatePreview();
}
});