Apply an image filter
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 button = document.getElementById('button');
const result = document.getElementById('result');
button.addEventListener('click', async function () {
const selection = cropper.getCropperSelection();
if (!selection) {
return;
}
const croppedCanvas = await selection.$toCanvas({
beforeDraw: function (context) {
context.filter = 'grayscale(100%)';
},
});
const croppedImage = document.createElement('img');
croppedImage.src = croppedCanvas.toDataURL();
result.replaceChildren(croppedImage);
});
});
</script>