Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I just built you a quick example of how to do it with jQuery: <a href="http://jsfiddle.net/gCqJ4/" rel="noreferrer">http://jsfiddle.net/gCqJ4/</a> It's not too hard and you can build off of my example. License is MIT.</p> <p>There is a fundamental assumption being made here. First, your image is expected to already have been uploaded; this is just the crop part. Second, the image has a data-id attribute which specified the id of the image that the server can use.</p> <p>I'll explain the JS a bit below:</p> <p>First part is your typical jQuery plugin declaration:</p> <pre><code>(function($) { $.fn.croppable = function(settings) { </code></pre> <p>Then we take an optional argument of settings, with some sane defaults (success being your anonymous function for handling successful data submissions):</p> <pre><code> settings = settings || { square: 50, default: 'middle', id: $(this).data("id"), success: null }; </code></pre> <p>Next is just basic initial position calculation.</p> <pre><code> var position = { x: settings.default == 'middle' ? ($(this).width() / 2) - (settings.square / 2) : 0 , y: settings.default == 'middle' ? ($(this).height() / 2) - (settings.square / 2) : 0 }; </code></pre> <p>We wrap the image in a container that can be styled and used as the parent containment for the draggable cropper.</p> <pre><code> $(this).wrap("&lt;div class='croppable-container' style='position: relative;' /&gt;"); </code></pre> <p>This is (obviously) the cropper.</p> <pre><code> var cropper = $("&lt;div style='position: absolute; top: " + position.y + "px; left: " + position.x + "px; height: " + settings.square + "px; width: " + settings.square + "px;' class='cropper' /&gt;"); </code></pre> <p>Place it before the image:</p> <pre><code> $(this).before(cropper); </code></pre> <p>Create a basic save button:</p> <pre><code> var save = $("&lt;input type='button' value='Crop Selection'/&gt;"); </code></pre> <p>And bind it to a service to receive posts for the cropping:</p> <pre><code> save.click(function () { $.post("/your/service/location", { img: id, x: cropper.position().left, y: cropper.position().top, height: settings.square }, function (data) { if (settings.success != null) { settings.success(data); } } ); }); $(this).parent().width($(this).width()); $(this).parent().height($(this).height()); cropper.draggable({containment: "parent"}); $(this).parent().after(save); </code></pre> <p>End of the typical plugin declaration:</p> <pre><code> }; })(jQuery); </code></pre> <p>Call it:</p> <pre><code>$(".croppable").croppable(); </code></pre> <p>As a final note, the plugin itself is only 1.61 KB. Small enough?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload