Using The CropGuide JavaScript API

CropGuide fires a selection of events to make it easier to integrate CropGuide with your webpage.

Use the file input field below and see the CropGuide events and their contents logged to your browser developer console.

We can listen for CropGuide events on the document object, we don’t have to wait for CropGuide to load.

<input type="file" />

<script>
    document.addEventListener('$cropguide:process', (e) => {
        console.log('The source image', e.detail.src);
        console.log('The output image', e.detail.dest);
    });
</script>

See below for an overview of all the events CropGuide fires.

Events

Init

$cropguide:init is fired when CropGuide initialises, if this event doesn’t fire then either CropGuide is not supported on the browser or the script failed to load.

Load

$cropguide:load is fired when CropGuide is ready.

Open

$cropguide:open fires when the editor modal opens.

Close

$cropguide:close fires when the editor modal closes.

Intercept

$cropguide:intercept fires when CropGuide intercepts a file selection. The detail property of the event is set to the original event object.

document.addEventListener('$cropguide:intercept', (e) => {
    console.log('The original file input event', e.detail);
});

Process

$cropguide:process fires when CropGuide has generated a new image, the detail property of the event is set to { src, dest } an object containing both the original file and the resulting image.

Invalid

$cropguide:invalid fires when CropGuide determines the selected image is too small to process. The detail property of the event is set to { src } an object containing the original image file.

Error

$cropguide:error fires when an error has occurred. The detail property of the event is set to { src, error } an object containing the original image file and an error object.

Ignore

$cropguide:ignore fires when the editor ignores a file, for example when it’s not an image. The detail property is set to { src }, src being the file object that is ignored.

Example

In the example below we use CropGuide to offer the resulting image as a download to the user.

<input type="file" />

<script>
    document.addEventListener('$cropguide:process', (e) => {
        downloadFile(e.detail.dest);
    });

    function downloadFile(file) {
        // Create a link and set the URL using `createObjectURL`
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = URL.createObjectURL(file);
        link.download = file.name;

        // It needs to be added to the DOM so it can be clicked
        document.body.appendChild(link);
        link.click();

        // To make this work on Firefox we need to wait
        // a little while before removing it.
        setTimeout(() => {
            URL.revokeObjectURL(link.href);
            link.parentNode.removeChild(link);
        }, 0);
    }
</script>