Redact part of an image
Image
Result
Source Code
<img id="image" src="/cropperjs/picture.jpg" alt="Picture">
<script src="https://unpkg.com/cropperjs@2/dist/cropper.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
const cropper = Cropper.createCropper('#image');
const image = document.getElementById('image');
const button = document.getElementById('button');
const result = document.getElementById('result');
button.addEventListener('click', function () {
const cropperCanvas = cropper.getCropperCanvas();
const cropperImage = cropper.getCropperImage();
const selection = cropper.getCropperSelection();
if (!cropperCanvas || !cropperImage || !selection) {
return;
}
const imageRect = cropperImage.getBoundingClientRect();
const selectionRect = selection.getBoundingClientRect();
const scaleX = image.naturalWidth / imageRect.width;
const scaleY = image.naturalHeight / imageRect.height;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = image.naturalWidth;
canvas.height = image.naturalHeight;
context.drawImage(image, 0, 0);
context.fillStyle = '#000';
context.fillRect(
(selectionRect.left - imageRect.left) * scaleX,
(selectionRect.top - imageRect.top) * scaleY,
selectionRect.width * scaleX,
selectionRect.height * scaleY,
);
const maskedImage = document.createElement('img');
maskedImage.src = canvas.toDataURL();
result.replaceChildren(maskedImage);
});
});
</script>