Skip to content

Commit

Permalink
Refactor to use pixels for units (#253)
Browse files Browse the repository at this point in the history
  • Loading branch information
sekoyo authored Apr 15, 2019
1 parent 9b65e4d commit de05e49
Show file tree
Hide file tree
Showing 8 changed files with 1,278 additions and 314 deletions.
85 changes: 33 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# React Image Crop

A responsive image cropping tool for React.
An image cropping tool for React with no dependencies.

[![React Image Crop on NPM](https://img.shields.io/npm/v/react-image-crop.svg)](https://www.npmjs.com/package/react-image-crop)

Expand All @@ -17,17 +17,15 @@ A responsive image cropping tool for React.
6. [FAQ](#faq)
1. [What about showing the crop on the client?](#what-about-showing-the-crop-on-the-client)
2. [How to handle image EXIF orientation/rotation](#how-to-handle-image-exif-orientationrotation)
3. [How to create a fixed aspect crop programmatically](#how-to-create-a-fixed-aspect-crop-programmatically)
7. [Contributing / Developing](#contributing--developing)

## Features

- Responsive
- Touch enabled
- Free-form or fixed aspect crops
- Keyboard support for nudging selection
- Min/max crop size
- No dependencies/small footprint (~4.5KB gzip)
- No dependencies/small footprint (5KB gzip)

## Installation
```
Expand All @@ -36,11 +34,9 @@ npm i react-image-crop --save

## Usage

Include the main js module, e.g.:
Include the main js module:

```js
var ReactCrop = require('react-image-crop');
// or es6:
import ReactCrop from 'react-image-crop';
```

Expand Down Expand Up @@ -75,9 +71,9 @@ Note when importing the script globally using a `<script>` tag access the compon

You can of course pass a blob url (using `URL.createObjectURL()` and `URL.revokeObjectURL()`) or base64 data.

#### onChange(crop, pixelCrop) (required)
#### onChange(crop) (required)

A callback which happens for every change of the crop (i.e. many times as you are dragging/resizing). Passes the current crop state object, as well as a pixel-converted crop for your convenience.
A callback which happens for every change of the crop (i.e. many times as you are dragging/resizing). Passes the current crop state object.

Note you _must_ implement this callback and update your crop state, otherwise nothing will change!

Expand All @@ -89,16 +85,16 @@ onChange = (crop) => {

#### crop (required*)

All crop values are in percentages, and are relative to the image. All crop params are optional.
All crop values are in pixels. All crop params are optional.

&#42; _While you can initially omit the crop object, any subsequent change will need to be saved to state in the `onChange` callback and passed here._

```js
crop: {
x: 20,
y: 10,
width: 30,
height: 10
x: 130,
y: 50,
width: 200,
height: 200
}

<ReactCrop src="path/to/image.jpg" crop={this.state.crop} />
Expand All @@ -112,7 +108,7 @@ crop: {
}
```

Or specify one of the dimensions:
Or specify one or both of the dimensions:

```js
crop: {
Expand All @@ -121,23 +117,23 @@ crop: {
}
```

In this case the other dimension will be calculated and `onChange` and `onComplete` will be fired with the completed crop, so that the crop will be rendered on the next pass. This will be done for you when an image is loaded, but if you want to set an aspect crop from say a button, then you will need to set a complete crop, see [How to create a fixed aspect crop programmatically](README.md#how-to-create-a-fixed-aspect-crop-programmatically) for more details on that.
If you specify just one of the dimensions, the other will be calculated for you.

#### minWidth (optional)

A minimum crop width, as a percentage of the image width.
A minimum crop width, in pixels.

#### minHeight (optional)

A minimum crop height, as a percentage of the image height.
A minimum crop height, in pixels.

#### maxWidth (optional)

A maximum crop width, as a percentage of the image width.
A maximum crop width, in pixels.

#### maxHeight (optional)

A maximum crop height, as a percentage of the image height.
A maximum crop height, in pixels.

#### keepSelection (optional)

Expand All @@ -163,17 +159,13 @@ Inline styles object to be passed to the image wrapper element.

Inline styles object to be passed to the image element.

#### useNaturalImageDimensions (optional)
#### onComplete(crop) (optional)

If true then the pixel crop is calculated using natural dimensions instead of the rendered dimensions (defaults to true).
A callback which happens after a resize, drag, or nudge. Passes the current crop state object.

#### onComplete(crop, pixelCrop) (optional)
#### onImageLoaded(image) (optional)

A callback which happens after a resize, drag, or nudge. Passes the current crop state object, as well as a pixel-converted crop for your convenience.

#### onImageLoaded(image, pixelCrop) (optional)

A callback which happens when the image is loaded. Passes the image DOM element and the pixelCrop if a crop has been specified by this point.
A callback which happens when the image is loaded. Passes the image DOM element.

#### onImageError(event) (optional)

Expand Down Expand Up @@ -206,26 +198,27 @@ However here's a ready to use function that returns a file blob for the cropped
```js
/**
* @param {File} image - Image File Object
* @param {Object} pixelCrop - pixelCrop Object from the 2nd argument of onChange or onComplete
* @param {Object} crop - crop Object
* @param {String} fileName - Name of the returned file in Promise
*/
function getCroppedImg(image, pixelCrop, fileName) {

function getCroppedImg(image, crop, fileName) {
const canvas = document.createElement('canvas');
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
const ctx = canvas.getContext('2d');

ctx.drawImage(
image,
pixelCrop.x,
pixelCrop.y,
pixelCrop.width,
pixelCrop.height,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
pixelCrop.width,
pixelCrop.height
crop.width,
crop.height,
);

// As Base64 string
Expand All @@ -241,7 +234,7 @@ function getCroppedImg(image, pixelCrop, fileName) {
}

async test() {
const croppedImg = await getCroppedImg(image, pixelCrop, returnedFileName);
const croppedImg = await getCroppedImg(image, crop, fileName);
}
```

Expand All @@ -259,18 +252,6 @@ You might find that some images are rotated incorrectly. Unfortunately this is a

You can use the following library to load images, which will correct the rotation for you: https://github.com/blueimp/JavaScript-Load-Image/

### How to create a fixed aspect crop programmatically

As this library uses percentages for crop values, creating an aspect crop yourself requires you to use the dimensions of the image. You might do this for instance if you have some buttons with pre-defined aspect crops.

The library exports a convenience function for this - `makeAspectCrop(partialCrop, imageAspect)`. You can calculate the image aspect using `image` which is passed in the `onImageLoaded(image, crop)` event. Note that you don't need to do this when a new image loads, in that case the library will fix (or complete if you omited width or height) the crop for you.

When using `makeAspectCrop` specify the aspect, optionally the x and y, and the width or height as a percentage. The other side will be filled in for you.

```js
const newCrop = makeAspectCrop({ aspect: 16/9, width: 50 }, image.naturalWidth / image.naturalHeight)
```

## Contributing / Developing

To develop run `npm start`, this will recompile your JS and SCSS on changes.
Expand Down
39 changes: 20 additions & 19 deletions demo/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class App extends PureComponent {
crop: {
x: 10,
y: 10,
aspect: 1,
// aspect: 1,
width: 50,
},
}
Expand All @@ -30,14 +30,14 @@ class App extends PureComponent {
}
}

onImageLoaded = (image, pixelCrop) => {
onImageLoaded = (image) => {
this.imageRef = image;
this.makeClientCrop(this.state.crop, pixelCrop);
this.makeClientCrop(this.state.crop);
}

onCropComplete = (crop, pixelCrop) => {
console.log('onCropComplete', { crop, pixelCrop });
this.makeClientCrop(crop, pixelCrop);
onCropComplete = (crop) => {
console.log('onCropComplete', crop);
this.makeClientCrop(crop);
}

onCropChange = (crop) => {
Expand All @@ -53,23 +53,24 @@ class App extends PureComponent {
console.log('onDragEnd');
}

getCroppedImg(image, pixelCrop, fileName) {
console.log('getCroppedImg', { image, pixelCrop, fileName });
getCroppedImg(image, crop, fileName) {
const canvas = document.createElement('canvas');
canvas.width = pixelCrop.width;
canvas.height = pixelCrop.height;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
const ctx = canvas.getContext('2d');

ctx.drawImage(
image,
pixelCrop.x,
pixelCrop.y,
pixelCrop.width,
pixelCrop.height,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
pixelCrop.width,
pixelCrop.height,
crop.width,
crop.height,
);

return new Promise((resolve) => {
Expand All @@ -82,11 +83,11 @@ class App extends PureComponent {
});
}

makeClientCrop(crop, pixelCrop) {
makeClientCrop(crop) {
if (this.imageRef && crop.width && crop.height) {
this.getCroppedImg(
this.imageRef,
pixelCrop,
crop,
'newFile.jpeg',
).then(croppedImageUrl => this.setState({ croppedImageUrl }));
}
Expand All @@ -100,7 +101,7 @@ class App extends PureComponent {
bottom: -25,
right: 0,
}}
onClick={() => window.alert('You click addon!')}
onClick={() => window.alert('You clicked the addon!')}
>
custom addon
</button>
Expand Down
Loading

0 comments on commit de05e49

Please sign in to comment.