如何给cropper.js一个固定的高度和宽度来进行相应的裁剪



我使用的是cropper.js v0.8.0

我使用下面的jQuery代码来裁剪图像。

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_view').attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
setTimeout(initCropper, 1000);
}
function initCropper(){
// console.log("Came here")
var image = document.getElementById('img_view');
var cropper = new Cropper(image, {
aspectRatio: 1/1,
cropBoxResizable: false,
crop: function(e) {
// console.log(e.detail.x);
// console.log(e.detail.y);
}
});
// On crop button clicked
document.getElementById('crop_button').addEventListener('click', function(){
var imgurl =  cropper.getCroppedCanvas().toDataURL();
var img = document.createElement("img");
img.src = imgurl;
document.getElementById("cropped_result").appendChild(img);
/* ---------------- SEND IMAGE TO THE SERVER-------------------------
cropper.getCroppedCanvas().toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
// Use `jQuery.ajax` method
$.ajax('/path/to/upload', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
*/
})
}

默认情况下,每当出现裁剪区域来裁剪图像时,默认情况下按纵横比进行裁剪。我希望它裁剪成特定的高度和宽度,比如420x230。我试过

maxCropBoxWidth: 420,
maxCropBoxHeight: 230,

minCropBoxWidth: 420,
minCropBoxHeight: 230,

以下是我的HTML代码:

<div class="custom-file">
<input type="file" id="post_featured_image" name="post_featured_image" class="custom-file-input" onchange="readURL(this);" />
<div class="image_container">
<img id="img_view" class="fixed-size-crop-box" src="#" alt="This is How the Featured Image will Look Exactly..">
</div>
<div id="cropped_result"></div>
<button id="crop_button">Crop</button>
<label class="custom-file-label" for="post_featured_image">Choose file</label>
</div>

但仍然没有成功。如果代码中有任何错误,或者由于较低版本而不起作用,有人能帮我更新版本吗。这将非常有帮助。M坚持了10个小时。

也许这就解决了你的问题。

var cropper = new Cropper(image, {
dragMode: 'move',
autoCropArea: 0.65,
restore: false,
guides: false,
center: false,
highlight: false,
cropBoxMovable: false,
cropBoxResizable: false,
toggleDragModeOnDblclick: false,
data:{ //define cropbox size
width: 240,
height:  90,
},
});

我已经尝试过了,它很有效,你可以找到有用的

const image = document.getElementById('crop_img');
const cropper = new Cropper(image, {
preview: '.preview',
viewMode: 2,
modal: true,
cropBoxResizable: false,

ready: function () {
cropper.setCropBoxData({
width: 150,
height: 150,
});


},

});
<img src="~/images/demo_img.jpg" id="crop_img" />

相关内容

  • 没有找到相关文章

最新更新