In this episode, we get Cropper.js hooked up to our image upload modal so we can start cropping photos right in the browser. We start by installing Cropper.js via npm and importing both the JS and CSS into our project, making sure it's loaded properly. There's a small hiccup with the CSS import, but it's quickly sorted out.
Next, we dive into integrating Cropper.js with our modal using Alpine.js (which is already available via Livewire). We set up Alpine's x-data
to store our cropper instance and grab the image element with a ref. Then, we initialize the cropper with some default options—auto crop area, view mode, and a 1:1 square aspect ratio—so it looks nice and clean.
We run into a sneaky issue where the cropper doesn't size correctly because it's being initialized before the modal fully renders. No worries—we fix this by wrapping the initialization in Alpine's $nextTick
to make sure everything's rendered before Cropper takes over.
With a quick tweak to image sizing for full width and some padding on the container, we end up with a modal where you can choose and crop images smoothly. Now we're all set up to listen for crop events and get the cropped region's data for the next step. If you want to tweak the cropping experience, feel free to play around with those Cropper.js options!