JSFiddle - React, Tailwind, and code Playground
by NOVUSIDEA
HTML
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/cropper.min.css">
<script src="https://unpkg.com/[email protected]/dist/cropper.min.js"></script>
<div class="cropper">
<img class="canvas" src="data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==">
<input class="image" type="file" name="image">
<textarea class="copped" hidden></textarea>
</div>
CSS
.cropper {
position: relative;
width: 150px;
height: 150px;
}
.cropper .image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
border-radius: 50%;
opacity: 0;
z-index: 10;
}
.cropper .canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #ccc;
border-radius: 50%;
z-index: 5;
}
.cropper .cropper-container {
z-index: 15;
}
.cropper .canvas img {
display: block;
width: 100%;
height: auto;
}
.cropper .cropper-view-box, .cropper-face {
border-radius: 50%;
}
JavaScript
document.querySelector('.cropper .image').addEventListener('change', function (event) {
const files = event.target.files;
const reader = new FileReader();
reader.addEventListener('load', function () {
const image = document.querySelector('.cropper img.canvas');
image.src = reader.result;
const cropper = new Cropper(image, {
aspectRatio: 1,
autoCropArea: 1,
minContainerWidth: 150,
minContainerHeight: 150,
//minCropBoxWidth: 150,
//minCropBoxHeight: 150,
viewMode: 3,
crop(event) {
canvas = cropper.getCroppedCanvas({
width: 150,
height: 150,
});
canvas.toBlob(function (blob) {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function(){
document.querySelector('.cropper .copped').value = reader.result;
};
});
},
});
}, false);
if (files[0]) {
reader.readAsDataURL(files[0]);
}
});