imgAreaSelect Home

imgAreaSelect Examples

Callback Functions

Selection Area Preview

In the code snippet below, an onSelectChange callback function is used to implement a simple selection area preview.

function preview(img, selection) {
    var scaleX = 100 / (selection.width || 1);
    var scaleY = 100 / (selection.height || 1);
    $('#ferret + div > img').css({
        width: Math.round(scaleX * 400) + 'px',
        height: Math.round(scaleY * 300) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'

$(document).ready(function () {
    $('<div><img src="ferret.jpg" style="position: relative;" /><div>')
            float: 'left',
            position: 'relative',
            overflow: 'hidden',
            width: '100px',
            height: '100px'

    $('#ferret').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });

It's coming right for us!

Submitting Selection Coordinates

Usually, selecting an area of an image in JavaScript is just the first step, and the selected coordinates need to be submitted to a server-side application (built with PHP, ASP, or any other server-side technology) for further processing. For example, if you're implementing an image cropping interface, you need to send the coordinates to a server application, which then does the actual cropping and produces the final image.

To submit the selection coordinates (x1, y1, x2, and y2), create a form element in your HTML document and add a hidden input field for each coordinate:

<form action="crop.php" method="post">
  <input type="hidden" name="x1" value="" />
  <input type="hidden" name="y1" value="" />
  <input type="hidden" name="x2" value="" />
  <input type="hidden" name="y2" value="" />
  <input type="submit" name="submit" value="Submit" />

Then, initialize imgAreaSelect with an onSelectEnd callback function that fills the hidden input fields with coordinates retrieved from the selection object. In the code snippet below, the input elements are referenced by their names, with a [attribute=value] selector.

$(document).ready(function () {
        onSelectEnd: function (img, selection) {

And that's it. You can try it out below – select an area and click the "Submit" button. The page will reload, and the values received by the server will be displayed below the button.

A ladybug enjoying the fine afternoon.