I am trying to crop an image before uploading it, for this I rely on Cropperjs . The problem I run into is that when you select an image the first one loads without a problem, but if for whatever reason you select a different image again, Cropper always keeps the first image you select in input
I leave an example where you can reproduce what happens:
<!DOCTYPE html>
<html>
<head>
<title>ejemplo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.css" integrity="sha256-x8iLuq/BLgVhgqscHiKrBZFP60kV2Xuilmpqy7kD/vI=" crossorigin="anonymous" />
</head>
<body>
<input type="file" id="inputImage" name="image" accept="image/*">
<div>
<img id="img">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.js" integrity="sha256-U/8sUxL62BDCJvl8Dmu1uuTtKilSrHytsP3XfgCJZwo=" crossorigin="anonymous"></script>
<script>
const inputImage = document.getElementById('inputImage');
const img = document.getElementById('img');
inputImage.addEventListener('change', function (e) {
let files = e.target.files;
img.src = URL.createObjectURL(files[0]);
new Cropper(img, {
aspectRatio: 4/3,
});
});
</script>
</body>
</html>
Finally I have already been able to find a solution, even though I had already tried something similar before and it didn't work for me, basically the idea is to check if it
img.src
has any value, if it doesn't have a value, I create the Cropper, otherwise I destroy the cropper and use replace to pass the new image.