Cropper.js
Applying a size range
by cormip
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
<p>
Original image is 450px x 450px. Container is <span id="divWidth"></span>px x <span id="divHeight"></span>px
</p>
<div id="cropperContainer">
<img id="image" src="https://upload.wikimedia.org/wikipedia/commons/c/c6/Cd-demons.jpg" />
</div>
<button id="btnCrop">Crop</button>
<img id="imgPreview" />
CSS
#cropperContainer {
border: 1px solid red;
width: 75vw;
height: 75vw;
background: #666;
}
img {
display: block;
max-width: 100%;
}
JavaScript
window.onload = function() {
let containerWidth = document.getElementById("cropperContainer").clientWidth,
isResizing = false,
btnCrop = document.getElementById("btnCrop");
btnCrop.onclick = function() {
doCrop()
}
function doResize() {
console.log("doResize")
containerWidth = cropper.getContainerData().width
elWidth.innerHTML = containerWidth
elHeight.innerHTML = containerWidth
if (img.width<=containerWidth && img.height<=containerWidth) {
const xy = (containerWidth/2-img.width/2)
cropper.setCropBoxData({left: xy, top: xy, width: img.width, height: img.height})
cropper.moveTo(xy, xy)
cropper.zoomTo(1)
}
isResizing = false
}
function doZoom(ratio) {
console.log("doZoom")
containerWidth = cropper.getContainerData().width
if (img.width<=containerWidth && img.height<=containerWidth && ratio > 1) {
cropper.zoomTo(1) //does nothing
}
}
function doCrop() {
const src = cropper.getCroppedCanvas({
minWidth: 250,
minHeight: 250,
maxWidth: 1024,
maxHeight: 1024,
imageSmoothingQuality: 'high'
}).toDataURL('image/jpeg')
console.log(src)
imgPreview.src = src
}
const
img = document.getElementById('image'),
imgPreview = document.getElementById('imgPreview'),
elWidth = document.getElementById('divWidth'),
elHeight = document.getElementById('divHeight'),
cropper = new Cropper(img, {
aspectRatio: 1,
viewMode: 1,
minCanvasWidth: 250,
minCanvasHeight: 250,
minCropBoxWidth: 250,
minCropBoxHeight: 250,
ready(event) {
doResize()
},
crop(event) {
console.log("crop:")
/* behaves erratically when...