Details

Version 1.2.1
Last updated 6th October 2009
Requirements
Demo View demo page
Links
License BSD License
Changelog
1.2.1
  • Added support for latest versions of Prototype & script.aculo.us (1.6.1.0 & 1.8.2 respectively). Changes provided by Tom Hirashima.
  • No-longer package prototype & script.aculo.us with the release
  • Changed tests to use google ajax libraries api to load prototype & script.aculo.us
  • Added option to not auto include the cropper CSS file
  • #00008 - Fixed bug: Dynamic include of cropper CSS expected cropper.js and failed when using cropper.uncompressed.js
  • #00028 - Fixed bug: Doesn't work with latest script.aculo.us - Fix by Tom Hirashima
  • #00030 - Fixed bug: Doesn't work in Firefox 3.5 (CSS include issue)
  • #00007 - Fixed bug: onEndCrop isn't called when moving with keys
  • #00011 - Fixed bug: The image that is to be cropped does not show in IE6.0 -- included CSS fix
  • Tidied up source code & fixed issues that jslint found so it will compress better
1.2.0
  • Added id to the preview image element using 'imgCrop_[originalImageID]'
  • #00001 - Fixed bug: Doesn't account for scroll offsets
  • #00009 - Fixed bug: Placing the cropper inside differently positioned elements causes incorrect co-ordinates and display
  • #00013 - Fixed bug: I-bar cursor appears on drag plane
  • #00014 - Fixed bug: If ID for image tag is not found in document script throws error
  • Fixed bug with drag start co-ordinates if wrapper element has moved in browser (e.g. dragged to a new position)
  • Fixed bug with drag start co-ordinates if image contained in a wrapper with scrolling - this may be buggy if image has other ancestors with scrolling applied (except the body)
  • #00015 - Fixed bug: When cropper removed and then reapplied onEndCrop callback gets called multiple times, solution suggestion from Bill Smith
  • Various speed increases & code cleanup which meant improved performance in Mac - which allowed removal of different overlay methods for IE and all other browsers, which led to a fix for:
  • #00010 - Fixed bug: Select area doesn't adhere to image size when image resized using img attributes
  • #00006 - Removed default behaviour of automatically setting a ratio when both min width & height passed, the ratioDimensions must be passed in
  • #00005 - Added ability to set maximum crop dimensions, if both min & max set as the same value then we'll get a fixed cropper size on the axes as appropriate and the resize handles will not be displayed as appropriate
  • Switched keydown for keypress for moving select area with cursor keys (makes for nicer action) - doesn't appear to work in Safari
1.1.3
  • Fixed wrong cursor on western handle in CSS
  • #00008 & #00003 - Added feature: Allow to set dimensions & position for cropper on load
  • #00002 - Fixed bug: Pressing 'remove cropper' twice removes image in IE
1.1.2
  • Fixed bugs with ratios when GCD is low (patch submitted by Andy Skelton)
1.1.1
  • Fixed bug with rendering issues fix in IE 5.5
  • Fixed bug with endCrop callback issues once cropper had been removed & reset in IE
1.1.0
  • Fixed bug with IE constantly trying to reload select area background image
  • Applied more robust fix to Safari & IE rendering issues
  • Added method to reset parameters - useful for when dynamically changing img the cropper is attached to
  • Added method to remove cropper from image
1.0.0
  • Initial verison

About

The JavaScript image cropper UI allows the user to crop an image using an interface with the same features and styling as found in commercial image editing software, and is is based on the Prototype JavaScript framework and script.aculo.us.

Initially I performed quite a lot of searching for some ready made solutions to meet my requirements, but found none that had the complete feature set that I required or any complete versions based on Prototype.

So after a week and a half of work, I present the JavaScript image cropper UI, built on Prototype & script.aculo.us.

Features

Screen shot of cropper in action

  • Un-obtrusive
  • Based on Prototype and script.aculo.us
  • Image editing package styling & functionality, the crop area functions and looks like those found in popular image editing software
  • Dynamic inclusion of required styles
  • Drag to draw areas
  • Shift drag to draw/resize areas as squares
  • Selection area can be moved
  • Selection area can be resized using resize handles
  • Allows dimension ratio limited crop areas
  • Allows minimum dimension crop areas
  • Allows maximum dimensions crop areas, if both min & max set as the same value then we'll get a fixed cropper size on the axes as appropriate and the resize handles will not be displayed as appropriate
  • Allows dynamic preview of resultant crop (if minimum width & height are provided), this is implemented as a subclass so can be removed if not required
  • Movement of selection area by arrow keys (shift + arrow key will move selection area by 10 pixels)
  • All operations stay within bounds of image
  • All functionality & display compatible with most popular browsers supported by Prototype, tested in:
    • PC: IE 6 & 5.5, Firefox 1.5, Opera 8.5 (see known issues) & 9.0b
    • MAC: Camino 1.0, Firefox 1.5, Safari 2.0

Usage

Extract to a directory of your choosing e.g. 'scripts/cropper/' and include the script and the required Prototype & script.aculo.us scripts:

HTML:
  1. <script type="text/javascript" src="scripts/cropper/lib/prototype.js" language="javascript"></script>
  2. <script type="text/javascript" src="scripts/cropper/lib/scriptaculous.js?load=effects,builder,dragdrop" language="javascript"></script>
  3. <script type="text/javascript" src="scripts/cropper/cropper.js" language="javascript"></script>

Options

ratioDim obj
The pixel dimensions to apply as a restrictive ratio, with properties x & y.
minWidth int
The minimum width for the select area in pixels.
minHeight int
The mimimum height for the select area in pixels.
maxWidth int
The maximum width for the select areas in pixels (if both minWidth & maxWidth set to same the width of the cropper will be fixed)
maxHeight int
The maximum height for the select areas in pixels (if both minHeight & maxHeight set to same the height of the cropper will be fixed)
displayOnInit int
Whether to display the select area on initialisation, only used when providing minimum width & height or ratio.
onEndCrop func
The callback function to provide the crop details to on end of a crop.
captureKeys boolean
Whether to capture the keys for moving the select area, as these can cause some problems at the moment.
onloadCoords obj
A coordinates object with properties x1, y1, x2 & y2; for the coordinates of the select area to display onload

The callback function

The callback function is a function that allows you to capture the crop co-ordinates when the user finished a crop movement, it is passed two arguments:

  • coords, obj, coordinates object with properties x1, y1, x2 & y2; for the coordinates of the select area.
  • dimensions, obj, dimensions object with properities width & height; for the dimensions of the select area.

An example function which outputs the crop values to form fields:

JavaScript:
  1. function onEndCrop( coords, dimensions ) {
  2.     $( 'x1' ).value = coords.x1;
  3.     $( 'y1' ).value = coords.y1;
  4.     $( 'x2' ).value = coords.x2;
  5.     $( 'y2' ).value = coords.y2;
  6.     $( 'width' ).value = dimensions.width;
  7.     $( 'height' ).value = dimensions.height;
  8. }

Basic interface

This basic example will attach the cropper UI to the test image and return crop results to the provided callback function.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2.  
  3.     <script type="text/javascript" language="javascript">
  4.     Event.observe( window, 'load', function() {
  5.         new Cropper.Img(
  6.             'testImage',
  7.             { onEndCrop: onEndCrop }
  8.         );
  9.     } );
  10. </script>

Minimum dimensions

You can apply minimum dimensions to a single axis or both, this example applies minimum dimensions to both axis.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2.  
  3. <script type="text/javascript" language="javascript">
  4.     Event.observe( window, 'load', function() {
  5.         new Cropper.Img(
  6.             'testImage',
  7.             {
  8.                 minWidth: 220,
  9.                 minHeight: 120,
  10.                 onEndCrop: onEndCrop
  11.             }
  12.         );
  13.     } );
  14. </script>

Select area ratio

You can apply a ratio to the selection area, this example applies a 4:3 ratio to the select area.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2.  
  3. <script type="text/javascript" language="javascript">
  4.     Event.observe( window, 'load', function() {
  5.         new Cropper.Img(
  6.             'testImage',
  7.             {
  8.                 ratioDim: {
  9.                     x: 220,
  10.                     y: 165
  11.                 },
  12.                 displayOnInit: true,
  13.                 onEndCrop: onEndCrop
  14.             }
  15.         );
  16.     } );
  17. </script>

With crop preview

You can display a dynamically produced preview of the resulting crop by using the ImgWithPreview subclass, a preview can only be displayed when we have a fixed size (set via minWidth & minHeight options). Note that the displayOnInit option is not required as this is the default behaviour when displaying a crop preview.

HTML:
  1. <img src="test.jpg" alt="Test image" id="testImage" width="500" height="333" />
  2. <div id="previewWrap"></div>
  3.  
  4. <script type="text/javascript" language="javascript">
  5.     Event.observe( window, 'load', function() {
  6.         new Cropper.ImgWithPreview(
  7.             'testImage',
  8.             {
  9.                 previewWrap: 'previewWrap',
  10.                 minWidth: 120,
  11.                 minHeight: 120,
  12.                 ratioDim: { x: 200, y: 120 },
  13.                 onEndCrop: onEndCrop
  14.             }
  15.         );
  16.     } );
  17. </script>

Known Issues

  • Safari animated gifs, only one of each will animate, this seems to be a known Safari issue.
  • After drawing an area and then clicking to start a new drag in IE 5.5 the rendered height appears as the last height until the user drags, this appears to be the related to another IE error (which has been fixed) where IE does not always redraw the select area properly.
  • Lack of CSS opacity support in Opera before version 9 mean we disable those style rules, if Opera 8 support is important you & you want the overlay to work then you can use the Opera rules in the CSS to apply a black PNG with 50% alpha transparency to replicate the effect.
  • Styling & borders on image, any CSS styling applied directly to the image itself (floats, borders, padding, margin, etc.) will cause problems with the cropper. The use of a wrapper element to apply these styles to is recommended.
  • overflow: auto or overflow: scroll on parent will cause cropper to burst out of parent in IE and Opera when applied (maybe Mac browsers too) I'm not sure why yet.

SEO Agency advanced JavaScript experience can enhance your site functionality. Adding the JavaScript Image Cropper is a good way to improve the user experience.

Next Steps

Feature Requests & Bug Reports

Please check the existing list of feature requests & bugs and the discussion list before posting requests or reporting bugs.

Leave a Tip

If you find this code useful you can leave a donation towards the continued development & support.

Discussion

Note: Please only use the comments for general comments and the discussion list to discuss this code project (e.g. implementation queries, change suggestions etc.).

Comments

There have been 667 comments so far, join the discussion.

Pages: « 3411 10 9 8 7 6 5 [4] 3 2 1 » Show All

80. Sune Kjaergaard - 1st Sep 2006 - 8:05 am

Hi again.

You’re probably right about the CSS bug. My initial suspicion was that the overlaying div’s lost their transparency. Having looked into the way the cropper is drawn in IE along with the fact that the image doesn’t reappear when resetting the cropper, tells me that this isn’t the problem.

The cropper is nested inside a div wich is again nested inside a td. Neither of those have any CSS positioning. Along with the cropper there is another div which is positioned with float:right, in the same parent div.
I’ll try to illustrate it:
[td]
[div]
[div style=”float:right;”][/div]
[div id=testWrap]the cropper[/div]
[/div]
[/td]

In case it’s an IE-CSS bug… Any ideas as for how to test for it and deal with it.

Regards
Sune

79. Dave - 31st Aug 2006 - 8:37 pm

All:
Again, thanks for the kind words, I can’t express that enough.

Alex:
The issue you raised is one of the known bugs, if you resize the image within the IMG tag then it won’t work properly in Firefox. The reason it works in IE is because IE implements the cropper in a different way to all other browsers, that is the original way which was far too slow when redrawing in Mac based browsers. I’ve looked at this problem and at the moment I’ve not come up with a fix for it. The only thing to do is resize the uploaded image to a maximum dimension for display with the cropper rather than resize with the IMG tag.

Sorry for the lack of a more robust solution at the moment.

Julio & Sune:
That sounds like it could be a bug with the CSS. it’s not something I’ve come across in IE in my testing, is the issue occuring when you implement the cropper inside some other elements positioned with CSS?

Rue:
I’m guessing you’ve got 1.1.2 or 1.1.3, I hadn’t noticed that the version number in the header of the uncompressed version hadn’t been changing, I’ve rectified that. I’ve also implemented your suggestion of making the ID unique on the previewImg by using the ‘imgCrop_’ prefix, this will be in the next release of the cropper, thanks for the heads up on that one.

Miri:
No it hasn’t been tested in IE7, I’m still waiting to get a standalone version of Beta 3 or the release candiate working reliably. However I just ran it quickly through my Beta 2 standalone version (which you should note is quite buggy in standalone mode) and the only problem I noticed were the marquees weren’t being resized properly. If anyone has the default installation of IE7 Beta 3 or Release Candidate (e.g. no registry hacks) then maybe they could verify it. But for now I can’t afford to lose the ability to test on IE6 for my other work.

78. Sune Kjaergaard - 31st Aug 2006 - 10:21 am

Hi Dave

First of all: what an excellent tool you’ve created. You’ve saved me loads of development time.

I’m integration your cropper into a CMS, but I have a bug, which as far as I can tell, only occurs in IE (ver 6.0.2900.2180). When the page with the cropper is first loaded, and I click inside the image to start selecting an area, the image disappears. I’m still able to select an area, but the image disappears beneath the overlaying div’s. If i reset the cropper, that is reinitializing it, the image is still gone. I am however able to load it in an object via javascript, meaning it exists somewhere in the DOM. Also I am able to see it in the DOM explorer of IE developer toolbar.
When I refresh the page the cropper will usually work without problems.
Any ideas as to where to start looking?

Regards
Sune

77. miri - 31st Aug 2006 - 4:06 am

Thank you so much! This is just what I needed. It runs smoothly and looks wonderful in Firefox and IE6. Has it been tested in IE7? (When I install IE7, it somehow resets my internet connection and I can’t access the internet…which kind of defeats the purpose of the darn thing.)

76. Rue - 29th Aug 2006 - 10:49 am

Before I start, some more flattery; you’ve saved me quite a few hours’ work, thanks!

I am currently writing a control panel extension to enable colour channel changes and other image processing functions to be called on the preview image. I came accross a bit of a DOM problem in that you clone the image node for the preview pane. This only becomes a real problem when you try to access it via the DOM to make changes. Rather than just tell you about it I have fixed it for you and post a diff here for you to check/integrate/laugh at.

This is a diff against the latest version of cropper.uncompressed.js (internally labelled as “v. 1.1.0 – 2006-06-02”)

CODE:

  1. DQoxMTk5ZDExOTgNCjwgICAgICAgICAgICAgICAgICAgICAgIHRoaXMucHJldmlld0ltZy5nZXRBdHRyaWJ1dGVOb2RlKCdpZCcpLnZhbHVlPSdpbWdDcm9wXycrdGhpcy5wcmV2aWV3SW1nLmdldEF0dHJpYnV0ZU5vZGUoJ2lkJykudmFsdWU7DQo=

The backend I am using is RoR but if anyone is interested in the js code I am producing to do the calls to refresh the preview and/or any of the ruby, I could easily be pursuaded. ;)

75. Julio Romano - 28th Aug 2006 - 7:36 pm

Congratulations!
This script is wonderful!
But i’m have a problem in IE.
I’m using the basic mode.
Sometimes, the image doesn’t appears. Then, i press F5, to refresh the page, and then, the image appears.
This problem doesn’t happen in Opera.
What is this?

Thanks

Julio Romano

74. Alex - 25th Aug 2006 - 4:01 am

First of all – you are the man!
This js is exactly what I’ve been looking for. Very very nice work and very generous of you to give it away. If I ever profit from it I will be sure to donate to your paypal.

Its working perfectly for me in IE, However in Firefox I’m noticing some interesting behavior – it seems that if I have an image thats actually 1600×1200 but I have displayed it onscreen as 400×300 the crop area shows the a ‘zoomed in’ area – i.e. if I am cropping x1:100, x2:300, y1:90, y2:210 with a width of 200 and a height of 120 the crop window shows the capture from the area of the original image. Its not scaling the coordinates. Does this make sense? I’m only seeing this in Firefox.

I’m wondering if this behavior is expected and if so is there a setting I should look into? Anyone else seeing this?

Thanks again for the great script.
Alex

73. Dave - 24th Aug 2006 - 7:28 pm

James:
Thanks for the kind comments on the Cropper and also thanks for stepping in with the reply to Tj’s question.

As for changing images dynamically with the ImgWithPreview class, I purposely didn’t add this feature when I added it to the main class as I wasn’t sure that the ImgWithPreview class would need it. Plus it would add a bit more overhead to both the classes as I’d have to create the hooks that call methods on the sub classes and also add all the logic for adding & removing the preview area.

I suppose it is a possibility so I’ve added it to the feature request list.

72. James Walker - 22nd Aug 2006 - 1:14 pm

TJ:

You’ll need to pass back the values to a server-side form and use something such as .NET, PHP etc to do the cropping…

71. Tj - 21st Aug 2006 - 10:16 pm

How are you supposed to crop the image to save it? I’ve looked around and couldn’t find anything… Thanks!

70. James Walker - 21st Aug 2006 - 9:35 pm

Firstly I have to say what a really neat bit of coding – very cool! I am having one prob though – I’m trying to change the image dynamically using ImgWithPreview but can’t seem to get it to work, despite whether i use remove(), reset() or setParams() – it either displays the last image or the current one distorted or a mixture of both! Yet it works fine with the standard Img object – the code i’ve found to use for this is:

if (curCrop != null)
{

curCrop.remove();
$(‘upimg’).src = tempFileName;
curCrop.setParams();

}
else
{
$(‘upimg’).src = tempFileName;

curCrop = new Cropper.Img(
‘upimg’,
{previewWrap: ‘previewWrap’,minWidth:96, minHeight:96, displayOnInit:1, ratioDim: { x: 1, y:1 }, onEndCrop: onEndCrop }
);
}

Any ideas?

Cheers

James

69. IGOR - 21st Aug 2006 - 2:27 pm

This is a really great script.
But how to save a cropped picture? Or just in Demo ist is not possible?
And i would like to know if it possible to have fixed cropped picture size?
Thanks!

68. Dave - 21st Aug 2006 - 10:52 am

Jim:
I’m glad that you found my Cropper UI useful.

Thomas:
The feature will be in the next release, I did want to try and tackle some of the other items on the list but haven’t had time. I’ll build the next release this evening and make it available.

67. Thomas Kenne - 21st Aug 2006 - 9:24 am

Hi,

on you feature list I can see that 0008 is checked. Does that mean that it is already implemented – and if so – how do I use it?

Thanks in advance

66. Jim - 21st Aug 2006 - 12:42 am

I work for a university and was designing a new administration with an image upload section in which they would select the most interesting area to crop out for thumbnails. I looked around the net for a good crop tool and did not find what I was looking for, so I threw together my own. I just recently stumbled across this one and was absolutely amazed! I will definitely throw out my horrible code and use this one! Thanks Dave!

65. mp - 17th Aug 2006 - 1:48 pm

Honestly, this is truely awesome! I am sooo jealous of your JS abilities. I thought about writing a simple JS cropper for an upcoming project (it would have been no where near the level of this) but I decided to take a look at what was out there first. I’m sure glad I did, because you are a genious.

64. Nathan Meurrens - 16th Aug 2006 - 7:11 pm

This is undoubtedly a really great script.
I was already using my own cropper but it is nothing compare to this one. I’ll definitely switch.

Thank you, Dave, for this work.

Anyway there is something I’ve miss…
Why are we passing through the EndCrop function at any click on the document? It may seems obvious for you but for me it isn’t. Actually I even don’t understand how does it happen and when is this function called.

Thanks again.

nathan

63. Nate - 15th Aug 2006 - 12:55 pm

Dave:
You can do whatever you want with the ASP code. I don’t have a public site, I’m using it on an intranet site.

62. Ashen-Shugar - 15th Aug 2006 - 6:51 am

Hello

It is super brilliant!

I would like to know if it possible to have fixed size or fixed a maxheight and/or maxwidth.

Thank you

61. Lucas Young - 15th Aug 2006 - 1:28 am

Hi! What a great tool!
Is it possible to have more than one cropper on a page?

cheers

Lucas

Pages:« 3411 10 9 8 7 6 5 [4] 3 2 1 » Show All

Leave a comment

No HTML please, only textile. For code please use [lang]...[/lang] tags (e.g. [html]...[/html] for HTML)