Select a portion of an image and retrieve its coordinates with jQuery

Nikolay picture Nikolay · Mar 22, 2012 · Viewed 24.1k times · Source

I need a way for user to select the portion of an image either by resizing transparent rectangle or by clicking and dragging the selection area (as it's done in desktop OS), both would work for me. Then i need to retrieve the coordinates of the selected area with jQuery.

Please recommend samples or tuts (if there are any), methods or API documentations sections that could help.

Answer

Mariusz Jamro picture Mariusz Jamro · Mar 22, 2012

See Jcrop and it's demos.

<!-- This is the image we're attaching Jcrop to -->
<img src="demo_files/pool.jpg" id="target" alt="Flowers" />

And the script:

<script type="text/javascript">

jQuery(function($){

  $('#target').Jcrop({
    onChange:   showCoords,
    onSelect:   showCoords
  });

});

// Simple event handler, called from onChange and onSelect
// event handlers to show an alert, as per the Jcrop 
// invocation above

function showCoords(c)
{
  alert('x='+ c.x +' y='+ c.y +' x2='+ c.x2 +' y2='+ c.y2)
  alert('w='+c.w +' h='+ c.h)
};

</script>