-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrop.stories.tsx
More file actions
113 lines (105 loc) · 2.7 KB
/
crop.stories.tsx
File metadata and controls
113 lines (105 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import type { Meta } from '@storybook/react-vite';
import { writeCanvas } from 'image-js';
import { useEffect, useRef, useState } from 'react';
import type { CommittedRoiProperties } from '../../src/index.ts';
import {
RoiContainer,
RoiList,
RoiProvider,
TargetImage,
useCommittedRois,
} from '../../src/index.ts';
import { Layout } from '../utils/Layout.tsx';
import { useLoadImage } from '../utils/useLoadImage.ts';
export default {
title: 'Full examples',
} as Meta;
const startRoi: CommittedRoiProperties = {
id: '0000-1111-2222-3333',
x: 0.35 * 320,
y: 0.35 * 320,
width: Math.floor(0.3 * 320),
height: Math.floor(0.3 * 320),
label: 'Roi A',
angle: 0,
};
export function CropImage() {
return (
<Layout>
<RoiProvider
initialConfig={{
commitRoiBoxStrategy: 'round',
selectedRoiId: startRoi.id,
mode: 'select',
rois: [startRoi],
}}
>
<RoiContainer
noUnselection
style={{ backgroundColor: 'black', borderRadius: '4px' }}
target={<TargetImage id="story-image" src="/barbara.jpg" />}
>
<RoiList
displayRotationHandle
showGrid
getOverlayOpacity={() => 0.6}
getStyle={(roi) => ({
resizeHandlerColor:
roi.action.type !== 'idle' ? 'rgba(255,255,255,0.5)' : 'white',
rectAttributes: {
fill: 'rgba(0,0,0,0.2)',
},
})}
/>
</RoiContainer>
<CroppedImage />
</RoiProvider>
</Layout>
);
}
function CroppedImage() {
const ref = useRef<HTMLCanvasElement>(null);
const roi = useCommittedRois()[0];
const image = useLoadImage('story-image', ref);
const [scale, setScale] = useState(2);
// Transform image
useEffect(() => {
if (!image) {
return;
}
const points = roi.getRectanglePoints();
const croppedImage = image.cropRectangle(
points.map((p) => ({
column: p.x,
row: p.y,
})),
);
if (ref.current) {
writeCanvas(croppedImage, ref.current);
}
}, [roi, image]);
return (
<>
<select
style={{ display: 'block' }}
defaultValue={2}
onChange={(event) => setScale(+event.target.value)}
>
<option value={1}>1x</option>
<option value={2}>2x</option>
<option value={4}>4x</option>
<option value={8}>8x</option>
<option value={16}>16x</option>
</select>
<canvas
ref={ref}
id="transformed-image"
style={{
transform: `scale(${scale})`,
transformOrigin: 'left top',
imageRendering: 'pixelated',
}}
/>
</>
);
}