Using cropper with a fixed aspect ratio and a specific display size of 150x200. Once an image is drawn to the canvas, the canvas (or rather its container) seems to expand to an even square or a 1:1 ratio. In my case, it becomes 200x200. There's an added space in one dimension that I do not want. (see the red areas in the pic link). The cropper box also doesn't appear to stick to the aspect ratio set. In the first example, the max crop box is 133x200, when it should be 150x200. In the second example its 105x158 which does match the the 2:3 ratio.
https://imgur.com/B0lwezD
I've tried setting dimensions on .cropper-container and .cropper-bg, but the image looks like its drawn with an offset on the canvas to center it within those square dimensions. So setting those containers really just ruins the UI, as the image becomes cropped yet the crop tool itself can expand beyond what you see. Is there a setting to control this?
$(function() {
var canvas = $("#canvas"),
context = canvas.get(0).getContext("2d"),
$result = $('#result');
$('#fileInput').on( 'change', function(){
if (this.files && this.files[0]) {
if ( this.files[0].type.match(/^image\//) ) {
var reader = new FileReader();
reader.onload = function(evt) {
var img = new Image();
img.onload = function() {
context.canvas.height = img.height;
context.canvas.width = img.width;
context.drawImage(img, 0, 0);
var cropper = canvas.cropper({
aspectRatio: 2/3,
viewMode: 2,
dragMode: 'move',
autoCropArea:1,
responsive: true,
});
$('#btnCrop').click(function() {
// Get a string base 64 data url
var croppedImageDataURL = canvas.cropper('getCroppedCanvas').toDataURL("image/png");
$result.append( $('<img>').attr('src', croppedImageDataURL) );
});
$('#btnRestore').click(function() {
canvas.cropper('reset');
$result.empty();
});
};
img.src = evt.target.result;
};
reader.readAsDataURL(this.files[0]);
}
else {
alert("Invalid file type! Please select an image file.");
}
}
else {
alert('No file(s) selected.');
}
});
});
img { max-width: 100%; }
#canvas {
height: 200px;
width: 150px;
cursor: default;
}
.cropper-bg{background-image:none !important;background-color:red;}
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.css" />
</head>
<body>
<p>
<!-- Below are a series of inputs which allow file selection and interaction with the cropper api -->
<input type="file" id="fileInput" accept="image/*" />
<input type="button" id="btnCrop" value="Crop" />
<input type="button" id="btnRestore" value="Restore" />
</p>
<div style="width:150px;height:200px;background:green;">
<canvas id="canvas">Your browser does not support the HTML5 canvas element.</canvas>
</div>
<div id="result"></div>
</body>
</html>