jCrop - update preview onload?

JasonS picture JasonS · Aug 31, 2011 · Viewed 8.3k times · Source

I am using the jCrop preview demo to do my own thing. However I have run into a problem. If I create a default selection when the image loads using setSelect: then I have the selection mapped out on the big image but it doesn't appear on the preview. I cannot find an api handler to call the updatePreview function when jCrop loads. Does anyone know how to call this function when jCrop loads?

jQuery(function($){

      // Create variables (in this scope) to hold the API and image size
      var jcrop_api, boundx, boundy;

      $('#target').Jcrop({
        onChange: updatePreview,
        onSelect: updatePreview,
        setSelect: [ 0, 0, selectWidth, selectHeight ],
        aspectRatio: 1
      },function(){
        // Use the API to get the real image size
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];
        // Store the API in the jcrop_api variable
        jcrop_api = this;
      });

      function updatePreview(c)
      {
        if (parseInt(c.w) > 0)
        {
          var rx = 100 / c.w;
          var ry = 100 / c.h;

          $('#preview').css({
            width: Math.round(rx * boundx) + 'px',
            height: Math.round(ry * boundy) + 'px',
            marginLeft: '-' + Math.round(rx * c.x) + 'px',
            marginTop: '-' + Math.round(ry * c.y) + 'px'
          });
        }
      };

    });

Answer

Eli picture Eli · Aug 14, 2012

Rather than the animateTo hack, you can just set the initial selection in the callback. So:

$('#target').Jcrop({
    onChange: updatePreview,
    onSelect: updatePreview,
    aspectRatio: 1
  },function(){
    // Use the API to get the real image size
    var bounds = this.getBounds();
    boundx = bounds[0];
    boundy = bounds[1];
    // Store the API in the jcrop_api variable
    jcrop_api = this;
    jcrop_api.setSelect([ 0, 0, selectWidth, selectHeight ]); // <--
  });