Search code examples
jqueryhamljcrop

How to display cropped region of image created via jcrop?


I am using jcrop to implement image cropping in my site.

enter image description here

enter image description here

After clicking on "confirm crop", I would expect the display area to be replaced by the newly cropped image.

My code is as follows:

//jquery method to display cropped image
coords_w = @options.media.get('crop_w')
coords_h = @options.media.get('crop_h')
coords_x = @options.media.get('crop_x')
coords_y = @options.media.get('crop_y')

img = new Image()
img.onload = () =>
  attachImage = () =>
    rx = img.width / coords_w
    ry = img.height / coords_h

    @$('.media_preview_display .image_holder').find('img').attr('src', @options.media.get('image_url'))
    @$('.media_preview_display .image_holder').find('img').css
      width: Math.round(rx * img.width) + 'px'
      height: Math.round(ry * img.height) + 'px'
      marginLeft: '-' + Math.round(rx * coords_x) + 'px'
      marginTop: '-' + Math.round(ry * coords_y) + 'px'

img.src = @options.media.get('image_url')

It's currently not displaying the cropped image correctly. How can I modify my code so that only the cropped region is displayed (as seen in my code, I have the x, y axis and height and width of the cropped aread)

//haml file
.section.media_preview_display.align_center
  .image_holder
    %img.jcrop{src: "<%= generic_object.image_url %>"}

Solution

  • Jcrop doesn't actually crop an image. You need something server side to take care of the actual cropping using the parameters gained from jcrop.

    You could get fancy with css position and size with overflow:hidden.