Skip to content

Commit 4e2dbfe

Browse files
Copilotmosch
andauthored
Merge remote-tracking branch 'origin/main' into fix/rotation-crop-boundary
# Conflicts: # CHANGELOG.md Co-authored-by: mosch <224866+mosch@users.noreply.github.com>
2 parents 31cdb41 + f9a5b97 commit 4e2dbfe

4 files changed

Lines changed: 263 additions & 77 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,16 @@
22

33
## Unreleased
44

5+
### Features
6+
7+
- **Responsive size** ([#399](https://github.com/mosch/react-avatar-editor/issues/399)) — `width` and `height` accept a percentage of the parent element (e.g. `width="100%"`), and the editor follows the parent when it resizes.
8+
59
### Bug Fixes
610

711
- **`position` prop is respected again** ([#436](https://github.com/mosch/react-avatar-editor/issues/436), [#437](https://github.com/mosch/react-avatar-editor/pull/437)) — since v15 the prop was ignored and images always started centered. It now sets the initial position, and changing it moves the crop area, as in v14.
812
- **Rotated images no longer show empty corners** ([#377](https://github.com/mosch/react-avatar-editor/issues/377)) — the drag boundary now accounts for `rotate`, so the crop area stays filled at any angle. If the image is not zoomed in enough to fill the rotated crop, it is centered.
13+
- **Changing `width` or `height` no longer reloads the image** — the loaded image is resized in place and keeps its position.
14+
- **The image is loaded once on mount** — it was loaded twice, so `onLoadStart` and `onLoadSuccess` fired twice.
915

1016
## 15.2.0 (2026-09-30)
1117

‎README.md‎

Lines changed: 43 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ function MyEditor() {
118118
}
119119
```
120120

121+
### Responsive size
122+
123+
`width` and `height` also accept a percentage of the parent element. The editor measures its parent and follows it when it resizes. A percentage sets the size of the whole canvas, and the crop area is that minus `border` on each side.
124+
125+
```tsx
126+
<div style={{ width: '100%', maxWidth: 600 }}>
127+
<AvatarEditor image={image} width="100%" height={300} border={20} />
128+
</div>
129+
```
130+
131+
The canvas becomes `display: block` in this mode. A percentage `height` needs a parent with a fixed height, as in CSS. Resizing keeps the image, position and zoom. The crop area just changes size.
132+
121133
### With drag and drop
122134

123135
Using [react-dropzone](https://github.com/react-dropzone/react-dropzone):
@@ -179,37 +191,37 @@ function MyEditor() {
179191

180192
## Props
181193

182-
| Prop | Type | Default | Description |
183-
| ----------------------- | -------------------- | ---------------- | --------------------------------------------------------------------------------------------- |
184-
| `image` | `string \| File` | | The URL or File object of the image to edit. |
185-
| `width` | `number` | `200` | Width of the crop area in pixels. |
186-
| `height` | `number` | `200` | Height of the crop area in pixels. |
187-
| `border` | `number \| number[]` | `25` | Border size around the crop area. Use an array `[horizontal, vertical]` for different values. |
188-
| `borderRadius` | `number` | `0` | Border radius of the crop area. Set to `width / 2` for a circle. |
189-
| `color` | `number[]` | `[0, 0, 0, 0.5]` | RGBA color of the crop mask overlay. |
190-
| `borderColor` | `number[]` | | RGBA color of the 1px border around the crop area. No border if omitted. |
191-
| `backgroundColor` | `string` | | Background color for transparent images (CSS color string). |
192-
| `scale` | `number` | `1` | Zoom level. `1` = fit, `> 1` = zoom in, `< 1` = zoom out (requires `disableBoundaryChecks`). |
193-
| `rotate` | `number` | `0` | Rotation in degrees. |
194-
| `position` | `{ x, y }` | | Center of the crop area (0–1 range). Set this + `onPositionChange` for controlled panning. |
195-
| `style` | `CSSProperties` | | Additional CSS styles for the canvas element. |
196-
| `crossOrigin` | `string` | | `crossOrigin` attribute for the image. Use `"anonymous"` for CORS images. |
197-
| `showGrid` | `boolean` | `false` | Show a rule-of-thirds grid overlay. |
198-
| `gridColor` | `string` | `"#666"` | Color of the grid lines. |
199-
| `disableBoundaryChecks` | `boolean` | `false` | Allow the image to be moved outside the crop boundary. |
200-
| `disableHiDPIScaling` | `boolean` | `false` | Disable `devicePixelRatio` scaling. Can improve performance on mobile. |
201-
| `disableCanvasRotation` | `boolean` | `true` | When `false`, the canvas resizes to fit the rotated image. |
202-
| `onLoadStart` | `() => void` | | Called when image loading begins. |
203-
| `onLoadSuccess` | `(image) => void` | | Called when the image loads successfully. |
204-
| `onLoadFailure` | `() => void` | | Called when the image fails to load. |
205-
| `onImageReady` | `() => void` | | Called when the image is first painted on the canvas. |
206-
| `onImageChange` | `() => void` | | Called on every visual change (drag, scale, rotate, etc.). |
207-
| `onMouseUp` | `() => void` | | Called when the user releases the mouse after dragging. |
208-
| `onMouseMove` | `(event) => void` | | Called on every mouse/touch move while dragging. |
209-
| `onPositionChange` | `(position) => void` | | Called when the crop position changes. Receives `{ x, y }`. |
210-
| `onRequestScaleChange` | `(scale) => void` | | Called when the user zooms via +/- keys, pinch, or wheel. Receives the requested new scale. |
211-
| `enableWheelZoom` | `boolean` | `false` | Zoom with the mouse wheel / trackpad. Requires `onRequestScaleChange`. |
212-
| `keyboardStep` | `number` | `1` | Pixels to move per arrow key press. Shift multiplies by 10. |
194+
| Prop | Type | Default | Description |
195+
| ----------------------- | -------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------- |
196+
| `image` | `string \| File` | | The URL or File object of the image to edit. |
197+
| `width` | `number \| string` | `200` | Width of the crop area in pixels, or a percentage like `"100%"` (see [Responsive size](#responsive-size)). |
198+
| `height` | `number \| string` | `200` | Height of the crop area in pixels, or a percentage like `"50%"`. |
199+
| `border` | `number \| number[]` | `25` | Border size around the crop area. Use an array `[horizontal, vertical]` for different values. |
200+
| `borderRadius` | `number` | `0` | Border radius of the crop area. Set to `width / 2` for a circle. |
201+
| `color` | `number[]` | `[0, 0, 0, 0.5]` | RGBA color of the crop mask overlay. |
202+
| `borderColor` | `number[]` | | RGBA color of the 1px border around the crop area. No border if omitted. |
203+
| `backgroundColor` | `string` | | Background color for transparent images (CSS color string). |
204+
| `scale` | `number` | `1` | Zoom level. `1` = fit, `> 1` = zoom in, `< 1` = zoom out (requires `disableBoundaryChecks`). |
205+
| `rotate` | `number` | `0` | Rotation in degrees. |
206+
| `position` | `{ x, y }` | | Center of the crop area (0–1 range). Set this + `onPositionChange` for controlled panning. |
207+
| `style` | `CSSProperties` | | Additional CSS styles for the canvas element. |
208+
| `crossOrigin` | `string` | | `crossOrigin` attribute for the image. Use `"anonymous"` for CORS images. |
209+
| `showGrid` | `boolean` | `false` | Show a rule-of-thirds grid overlay. |
210+
| `gridColor` | `string` | `"#666"` | Color of the grid lines. |
211+
| `disableBoundaryChecks` | `boolean` | `false` | Allow the image to be moved outside the crop boundary. |
212+
| `disableHiDPIScaling` | `boolean` | `false` | Disable `devicePixelRatio` scaling. Can improve performance on mobile. |
213+
| `disableCanvasRotation` | `boolean` | `true` | When `false`, the canvas resizes to fit the rotated image. |
214+
| `onLoadStart` | `() => void` | | Called when image loading begins. |
215+
| `onLoadSuccess` | `(image) => void` | | Called when the image loads successfully. |
216+
| `onLoadFailure` | `() => void` | | Called when the image fails to load. |
217+
| `onImageReady` | `() => void` | | Called when the image is first painted on the canvas. |
218+
| `onImageChange` | `() => void` | | Called on every visual change (drag, scale, rotate, etc.). |
219+
| `onMouseUp` | `() => void` | | Called when the user releases the mouse after dragging. |
220+
| `onMouseMove` | `(event) => void` | | Called on every mouse/touch move while dragging. |
221+
| `onPositionChange` | `(position) => void` | | Called when the crop position changes. Receives `{ x, y }`. |
222+
| `onRequestScaleChange` | `(scale) => void` | | Called when the user zooms via +/- keys, pinch, or wheel. Receives the requested new scale. |
223+
| `enableWheelZoom` | `boolean` | `false` | Zoom with the mouse wheel / trackpad. Requires `onRequestScaleChange`. |
224+
| `keyboardStep` | `number` | `1` | Pixels to move per arrow key press. Shift multiplies by 10. |
213225

214226
## Contributing
215227

‎packages/lib/src/__tests__/AvatarEditor.test.tsx‎

Lines changed: 128 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,25 @@
11
import React, { createRef } from 'react'
2-
import { render, fireEvent, waitFor } from '@testing-library/react'
2+
import { render, fireEvent, waitFor, act } from '@testing-library/react'
33
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
44
import AvatarEditor, { type AvatarEditorRef, useAvatarEditor } from '../index'
55

6+
// Makes every Image a 400x300 landscape image that loads as soon as src is set
7+
const mockImageLoad = () =>
8+
vi.spyOn(globalThis, 'Image').mockImplementation(function (
9+
this: HTMLImageElement,
10+
) {
11+
const listeners: Record<string, (() => void)[]> = {}
12+
this.addEventListener = (type: string, fn: () => void) => {
13+
;(listeners[type] ??= []).push(fn)
14+
}
15+
Object.defineProperty(this, 'src', {
16+
set: () => setTimeout(() => listeners['load']?.forEach((fn) => fn()), 0),
17+
})
18+
Object.defineProperty(this, 'width', { value: 400 })
19+
Object.defineProperty(this, 'height', { value: 300 })
20+
return this
21+
} as unknown as typeof Image)
22+
623
const cropCenter = (ref: React.RefObject<AvatarEditorRef | null>) => {
724
const rect = ref.current!.getCroppingRect()
825
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }
@@ -356,22 +373,7 @@ describe('AvatarEditor', () => {
356373

357374
describe('with a loaded image', () => {
358375
beforeEach(() => {
359-
// 400x300 landscape image that loads as soon as src is set
360-
vi.spyOn(globalThis, 'Image').mockImplementation(function (
361-
this: HTMLImageElement,
362-
) {
363-
const listeners: Record<string, (() => void)[]> = {}
364-
this.addEventListener = (type: string, fn: () => void) => {
365-
;(listeners[type] ??= []).push(fn)
366-
}
367-
Object.defineProperty(this, 'src', {
368-
set: () =>
369-
setTimeout(() => listeners['load']?.forEach((fn) => fn()), 0),
370-
})
371-
Object.defineProperty(this, 'width', { value: 400 })
372-
Object.defineProperty(this, 'height', { value: 300 })
373-
return this
374-
} as unknown as typeof Image)
376+
mockImageLoad()
375377
})
376378

377379
afterEach(() => {
@@ -613,4 +615,113 @@ describe('AvatarEditor', () => {
613615
fireEvent.keyDown(canvas, { key: 'ArrowUp' })
614616
})
615617
})
618+
// -------------------------------------------------------
619+
// Responsive width / height (#399)
620+
// -------------------------------------------------------
621+
describe('percentage width and height', () => {
622+
let parentWidth: number
623+
let resizeCallback: (() => void) | undefined
624+
625+
beforeEach(() => {
626+
parentWidth = 500
627+
resizeCallback = undefined
628+
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(
629+
() => parentWidth,
630+
)
631+
vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(
632+
300,
633+
)
634+
vi.stubGlobal(
635+
'ResizeObserver',
636+
class {
637+
constructor(cb: () => void) {
638+
resizeCallback = cb
639+
}
640+
observe() {}
641+
disconnect() {}
642+
},
643+
)
644+
})
645+
646+
afterEach(() => {
647+
vi.restoreAllMocks()
648+
vi.unstubAllGlobals()
649+
})
650+
651+
it('fills the given share of the parent, border included', () => {
652+
const { container } = render(
653+
<div>
654+
<AvatarEditor width="100%" height="50%" border={25} />
655+
</div>,
656+
)
657+
const canvas = container.querySelector('canvas')!
658+
expect(canvas.style.width).toBe('500px')
659+
expect(canvas.style.height).toBe('150px')
660+
expect(canvas.style.display).toBe('block')
661+
})
662+
663+
it('exports the crop area without the border', () => {
664+
const ref = createRef<AvatarEditorRef>()
665+
render(
666+
<div>
667+
<AvatarEditor ref={ref} width="100%" height={200} border={25} />
668+
</div>,
669+
)
670+
const exported = ref.current!.getImageScaledToCanvas()
671+
expect(exported.width).toBe(450)
672+
expect(exported.height).toBe(200)
673+
})
674+
675+
it('follows the parent when it resizes', () => {
676+
const { container } = render(
677+
<div>
678+
<AvatarEditor width="100%" height={200} border={0} />
679+
</div>,
680+
)
681+
const canvas = container.querySelector('canvas')!
682+
expect(canvas.style.width).toBe('500px')
683+
684+
parentWidth = 320
685+
act(() => resizeCallback?.())
686+
expect(canvas.style.width).toBe('320px')
687+
expect(canvas.getAttribute('width')).toBe('320')
688+
})
689+
690+
it('keeps numeric sizes unchanged and inline', () => {
691+
const { container } = render(
692+
<div>
693+
<AvatarEditor width={200} height={200} border={25} />
694+
</div>,
695+
)
696+
const canvas = container.querySelector('canvas')!
697+
expect(canvas.style.width).toBe('250px')
698+
expect(canvas.style.display).toBe('')
699+
})
700+
701+
it('does not reload the image when the size changes', async () => {
702+
const imageSpy = mockImageLoad()
703+
const onLoadSuccess = vi.fn()
704+
const { container } = render(
705+
<div>
706+
<AvatarEditor
707+
image="https://example.com/photo.jpg"
708+
width="100%"
709+
height={200}
710+
border={0}
711+
position={{ x: 0.4, y: 0.5 }}
712+
onLoadSuccess={onLoadSuccess}
713+
/>
714+
</div>,
715+
)
716+
await waitFor(() => expect(onLoadSuccess).toHaveBeenCalled())
717+
const loads = imageSpy.mock.calls.length
718+
719+
parentWidth = 300
720+
act(() => resizeCallback?.())
721+
722+
expect(container.querySelector('canvas')!.style.width).toBe('300px')
723+
expect(imageSpy.mock.calls.length).toBe(loads)
724+
expect(onLoadSuccess).toHaveBeenCalledTimes(1)
725+
})
726+
})
616727
})

0 commit comments

Comments
 (0)