Search code examples
javascriptjqueryjcrop

jCrop - update preview onload?


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'
          });
        }
      };

    });

Solution

  • I tried to set the default value and the default value is getting previewed in the preview box.

    jQuery(window).load(function(){
    
                jQuery('#cropbox').Jcrop({
                    onChange: showPreview,
                    onSelect: showPreview,
                    setSelect: [ 100, 0, 100, 100 ],
                    aspectRatio: 1
                });
    
            });
    

    This just worked the way i wanted. You might have some other error on your script. But you dont have to invoke anything special to have to show the preview. If you are not doing this onload then try doing it onload.