0
# Utility Functions
1
2
Helper functions for crop manipulation including aspect ratio enforcement, coordinate conversion, positioning utilities, and constraint handling.
3
4
## Capabilities
5
6
### Crop Creation and Positioning
7
8
Functions for creating and positioning crops with specific constraints and aspect ratios.
9
10
```typescript { .api }
11
/**
12
* Creates a crop with a fixed aspect ratio
13
* Adjusts dimensions to maintain the specified aspect ratio
14
* Function is overloaded to preserve input unit type
15
* @param crop - Initial crop configuration with unit specified
16
* @param aspect - Desired aspect ratio (width/height)
17
* @param containerWidth - Width of the container element
18
* @param containerHeight - Height of the container element
19
* @returns Crop with enforced aspect ratio in same unit as input
20
*/
21
function makeAspectCrop(
22
crop: Pick<PercentCrop, 'unit'> & Partial<Omit<PercentCrop, 'unit'>>,
23
aspect: number,
24
containerWidth: number,
25
containerHeight: number
26
): PercentCrop;
27
28
function makeAspectCrop(
29
crop: Pick<PixelCrop, 'unit'> & Partial<Omit<PixelCrop, 'unit'>>,
30
aspect: number,
31
containerWidth: number,
32
containerHeight: number
33
): PixelCrop;
34
35
/**
36
* Centers a crop within the container
37
* Calculates x,y coordinates to center the crop
38
* Function is overloaded to preserve input unit type
39
* @param crop - Crop to center (partial, requires unit and dimensions)
40
* @param containerWidth - Width of the container element
41
* @param containerHeight - Height of the container element
42
* @returns Crop centered within container bounds in same unit as input
43
*/
44
function centerCrop(
45
crop: Pick<PercentCrop, 'unit'> & Partial<Omit<PercentCrop, 'unit'>>,
46
containerWidth: number,
47
containerHeight: number
48
): PercentCrop;
49
50
function centerCrop(
51
crop: Pick<PixelCrop, 'unit'> & Partial<Omit<PixelCrop, 'unit'>>,
52
containerWidth: number,
53
containerHeight: number
54
): PixelCrop;
55
```
56
57
**Usage Examples:**
58
59
```typescript
60
import { makeAspectCrop, centerCrop } from "react-image-crop";
61
62
// Create a 16:9 aspect ratio crop
63
const aspectCrop = makeAspectCrop(
64
{ unit: '%', width: 80 }, // Start with 80% width
65
16 / 9, // 16:9 aspect ratio
66
1920, // Container width
67
1080 // Container height
68
);
69
70
// Create a centered square crop
71
const centeredCrop = centerCrop(
72
makeAspectCrop({ unit: '%' }, 1, 800, 600), // Square aspect
73
800, // Container width
74
600 // Container height
75
);
76
77
// Combine operations for centered aspect crop
78
const centeredAspectCrop = centerCrop(
79
makeAspectCrop(
80
{ unit: '%', width: 60, height: 40 },
81
4 / 3, // 4:3 aspect ratio
82
1024, 768
83
),
84
1024, 768
85
);
86
```
87
88
### Coordinate Conversion
89
90
Functions for converting between pixel and percentage coordinate systems.
91
92
```typescript { .api }
93
/**
94
* Converts crop coordinates to pixel units
95
* @param crop - Crop to convert (partial)
96
* @param containerWidth - Width of the container element
97
* @param containerHeight - Height of the container element
98
* @returns Crop with pixel coordinates
99
*/
100
function convertToPixelCrop(
101
crop: Partial<Crop>,
102
containerWidth: number,
103
containerHeight: number
104
): PixelCrop;
105
106
/**
107
* Converts crop coordinates to percentage units
108
* @param crop - Crop to convert (partial)
109
* @param containerWidth - Width of the container element
110
* @param containerHeight - Height of the container element
111
* @returns Crop with percentage coordinates
112
*/
113
function convertToPercentCrop(
114
crop: Partial<Crop>,
115
containerWidth: number,
116
containerHeight: number
117
): PercentCrop;
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
import { convertToPixelCrop, convertToPercentCrop } from "react-image-crop";
124
125
// Convert percentage crop to pixels for precise calculations
126
const percentCrop = { unit: '%', x: 25, y: 25, width: 50, height: 50 };
127
const pixelCrop = convertToPixelCrop(percentCrop, 800, 600);
128
// Result: { unit: 'px', x: 200, y: 150, width: 400, height: 300 }
129
130
// Convert pixel crop to percentage for responsive layouts
131
const pixelCropInput = { unit: 'px', x: 100, y: 75, width: 200, height: 150 };
132
const percentCropOutput = convertToPercentCrop(pixelCropInput, 800, 600);
133
// Result: { unit: '%', x: 12.5, y: 12.5, width: 25, height: 25 }
134
135
// Handle crops with missing properties (uses defaults)
136
const partialCrop = { unit: 'px', width: 100, height: 100 };
137
const fullPixelCrop = convertToPixelCrop(partialCrop, 800, 600);
138
// Result: { unit: 'px', x: 0, y: 0, width: 100, height: 100 }
139
```
140
141
### Crop Constraint and Validation
142
143
Functions for constraining crops within bounds and handling size limitations.
144
145
```typescript { .api }
146
/**
147
* Constrains a crop within container bounds and size limits
148
* Handles aspect ratio preservation and min/max constraints
149
* @param pixelCrop - Crop in pixel coordinates
150
* @param aspect - Aspect ratio to maintain (0 for free-form)
151
* @param ord - Drag handle ordinate being used
152
* @param containerWidth - Width of the container element
153
* @param containerHeight - Height of the container element
154
* @param minWidth - Minimum crop width in pixels (default: 0)
155
* @param minHeight - Minimum crop height in pixels (default: 0)
156
* @param maxWidth - Maximum crop width in pixels (default: containerWidth)
157
* @param maxHeight - Maximum crop height in pixels (default: containerHeight)
158
* @returns Constrained crop within all specified bounds
159
*/
160
function containCrop(
161
pixelCrop: PixelCrop,
162
aspect: number,
163
ord: Ords,
164
containerWidth: number,
165
containerHeight: number,
166
minWidth?: number,
167
minHeight?: number,
168
maxWidth?: number,
169
maxHeight?: number
170
): PixelCrop;
171
172
/**
173
* Nudges (adjusts) crop position/size based on keyboard input
174
* Used for keyboard accessibility and fine-tuning
175
* @param pixelCrop - Current crop in pixel coordinates
176
* @param key - Keyboard key pressed ('ArrowLeft', 'ArrowRight', etc.)
177
* @param offset - Amount to nudge in pixels
178
* @param ord - Drag handle ordinate being manipulated
179
* @returns Adjusted crop after applying nudge operation
180
*/
181
function nudgeCrop(
182
pixelCrop: PixelCrop,
183
key: string,
184
offset: number,
185
ord: Ords
186
): PixelCrop;
187
```
188
189
**Usage Examples:**
190
191
```typescript
192
import { containCrop, nudgeCrop } from "react-image-crop";
193
194
// Constrain crop within bounds with size limits
195
const unconstrainedCrop = { unit: 'px', x: -10, y: -5, width: 900, height: 700 };
196
const constrainedCrop = containCrop(
197
unconstrainedCrop,
198
16 / 9, // Maintain 16:9 aspect ratio
199
'se', // Southeast drag handle
200
800, 600, // Container size
201
100, 50, // Min width/height
202
600, 400 // Max width/height
203
);
204
205
// Keyboard nudging for fine adjustments
206
const currentCrop = { unit: 'px', x: 100, y: 100, width: 200, height: 150 };
207
const nudgedCrop = nudgeCrop(
208
currentCrop,
209
'ArrowRight', // Move right
210
10, // 10 pixels
211
'se' // From southeast handle
212
);
213
214
// Handle different keyboard modifiers
215
const smallNudge = nudgeCrop(currentCrop, 'ArrowUp', 1, 'n'); // 1px up
216
const mediumNudge = nudgeCrop(currentCrop, 'ArrowUp', 10, 'n'); // 10px up (Shift)
217
const largeNudge = nudgeCrop(currentCrop, 'ArrowUp', 100, 'n'); // 100px up (Ctrl/Cmd)
218
```
219
220
### Basic Utility Functions
221
222
Core utility functions for common operations and value manipulation.
223
224
```typescript { .api }
225
/**
226
* Default crop object with zero dimensions in pixel units
227
* Useful as a starting point for new crops
228
*/
229
const defaultCrop: PixelCrop;
230
231
/**
232
* Clamps a number between minimum and maximum values
233
* @param num - Number to clamp
234
* @param min - Minimum allowed value
235
* @param max - Maximum allowed value
236
* @returns Number clamped within bounds
237
*/
238
function clamp(num: number, min: number, max: number): number;
239
240
/**
241
* Conditional class name utility
242
* Filters out falsy values and joins remaining strings
243
* @param args - Array of class names (strings) or falsy values
244
* @returns Space-separated string of valid class names
245
*/
246
function cls(...args: unknown[]): string;
247
248
/**
249
* Compares two crop objects for equality
250
* Handles partial crop objects safely
251
* @param cropA - First crop (partial)
252
* @param cropB - Second crop (partial)
253
* @returns True if crops have identical properties
254
*/
255
function areCropsEqual(cropA: Partial<Crop>, cropB: Partial<Crop>): boolean;
256
```
257
258
**Usage Examples:**
259
260
```typescript
261
import { defaultCrop, clamp, cls, areCropsEqual } from "react-image-crop";
262
263
// Initialize new crop with defaults
264
const newCrop = { ...defaultCrop, width: 100, height: 100 };
265
266
// Clamp values within bounds
267
const clampedValue = clamp(150, 0, 100); // Result: 100
268
const clampedPosition = clamp(-10, 0, 800); // Result: 0
269
270
// Conditional class names
271
const className = cls(
272
'crop-container',
273
isActive && 'active',
274
isDisabled && 'disabled',
275
undefined, // Filtered out
276
'' // Filtered out
277
);
278
// Result: "crop-container active" (if isActive=true, isDisabled=false)
279
280
// Compare crops for changes
281
const oldCrop = { unit: 'px', x: 10, y: 10, width: 100, height: 100 };
282
const newCrop = { unit: 'px', x: 10, y: 10, width: 100, height: 100 };
283
284
if (!areCropsEqual(oldCrop, newCrop)) {
285
console.log('Crop has changed, update preview');
286
}
287
```
288
289
### Advanced Usage Patterns
290
291
Common patterns combining multiple utility functions for complex crop operations.
292
293
**Creating Responsive Aspect Crops:**
294
295
```typescript
296
import { makeAspectCrop, centerCrop, convertToPercentCrop } from "react-image-crop";
297
298
function createResponsiveAspectCrop(
299
aspect: number,
300
containerWidth: number,
301
containerHeight: number,
302
desiredSizePercent: number = 80
303
) {
304
// Create aspect crop with percentage coordinates
305
const aspectCrop = makeAspectCrop(
306
{ unit: '%', width: desiredSizePercent },
307
aspect,
308
containerWidth,
309
containerHeight
310
);
311
312
// Center the crop
313
const centeredCrop = centerCrop(aspectCrop, containerWidth, containerHeight);
314
315
// Ensure it's in percentage units for responsiveness
316
return convertToPercentCrop(centeredCrop, containerWidth, containerHeight);
317
}
318
319
// Usage
320
const responsiveCrop = createResponsiveAspectCrop(16/9, 1920, 1080, 70);
321
```
322
323
**Crop Validation and Correction:**
324
325
```typescript
326
import { convertToPixelCrop, containCrop, convertToPercentCrop } from "react-image-crop";
327
328
function validateAndCorrectCrop(
329
crop: Crop,
330
containerWidth: number,
331
containerHeight: number,
332
aspect?: number,
333
minWidth?: number,
334
minHeight?: number
335
): Crop {
336
// Convert to pixels for validation
337
const pixelCrop = convertToPixelCrop(crop, containerWidth, containerHeight);
338
339
// Apply constraints
340
const constrainedCrop = containCrop(
341
pixelCrop,
342
aspect || 0,
343
'se', // Default ordinate for general constraint
344
containerWidth,
345
containerHeight,
346
minWidth,
347
minHeight
348
);
349
350
// Convert back to original unit
351
return crop.unit === '%'
352
? convertToPercentCrop(constrainedCrop, containerWidth, containerHeight)
353
: constrainedCrop;
354
}
355
```