In this episode, we're digging into how to handle cropping events and passing cropped images through your app for instant preview. We start by hooking up our cropper so we can listen to cropping events as the user selects a region on the image. This gives us all the important values like the position and size of the crop box. We then create a little area in our component to store this crop region, and only use it when we actually need it.
Next, we slap on a nice "Done" button. When it's clicked, we grab the cropped portion of the image as a blob (fancy speak for raw image data), and use a browser-native method to show a preview instantly in the UI. We're not uploading or saving anything just yet—this is just for the user to see before making things permanent.
To communicate all this back and forth, we use Alpine's dispatch
to fire off a custom event (cropped-image-ready
) with both the new cropped image and all the values we need later for server-side resizing. Our parent field picks up this event, stores the blob, and instantly displays a preview of the cropped image. This way, the user can see exactly what they're about to upload!
We finish up by making sure the modal closes nicely after cropping, and tweak a few behaviors (like not letting people close the modal by clicking outside, if we want).
By the end, we've got cropping with live preview, robust event handling, and a neat, user-friendly workflow set up—ready for backend persistence in the next steps!