-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathAnnotations.tsx
91 lines (81 loc) · 2.51 KB
/
Annotations.tsx
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
import type { VNode, h as hType } from 'preact';
import type * as Hooks from 'preact/hooks';
import { DOCUMENT } from '../../constants';
interface FactoryParams {
h: typeof hType;
}
export default function AnnotationsFactory({
h, // eslint-disable-line @typescript-eslint/no-unused-vars
}: FactoryParams) {
return function Annotations({
action,
imageBuffer,
annotatingRef,
}: {
action: 'crop' | 'annotate' | '';
imageBuffer: HTMLCanvasElement;
annotatingRef: Hooks.Ref<HTMLCanvasElement>;
}): VNode {
const onAnnotateStart = (): void => {
if (action !== 'annotate') {
return;
}
const handleMouseMove = (moveEvent: MouseEvent): void => {
const annotateCanvas = annotatingRef.current;
if (annotateCanvas) {
const rect = annotateCanvas.getBoundingClientRect();
const x = moveEvent.clientX - rect.x;
const y = moveEvent.clientY - rect.y;
const ctx = annotateCanvas.getContext('2d');
if (ctx) {
ctx.lineTo(x, y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y);
}
}
};
const handleMouseUp = (): void => {
const ctx = annotatingRef.current?.getContext('2d');
if (ctx) {
ctx.beginPath();
}
// Add your apply annotation logic here
applyAnnotation();
DOCUMENT.removeEventListener('mousemove', handleMouseMove);
DOCUMENT.removeEventListener('mouseup', handleMouseUp);
};
DOCUMENT.addEventListener('mousemove', handleMouseMove);
DOCUMENT.addEventListener('mouseup', handleMouseUp);
};
const applyAnnotation = (): void => {
// Logic to apply the annotation
const imageCtx = imageBuffer.getContext('2d');
const annotateCanvas = annotatingRef.current;
if (imageCtx && annotateCanvas) {
imageCtx.drawImage(
annotateCanvas,
0,
0,
annotateCanvas.width,
annotateCanvas.height,
0,
0,
imageBuffer.width,
imageBuffer.height,
);
const annotateCtx = annotateCanvas.getContext('2d');
if (annotateCtx) {
annotateCtx.clearRect(0, 0, annotateCanvas.width, annotateCanvas.height);
}
}
};
return (
<canvas
class={`editor__annotation ${action === 'annotate' ? 'editor__annotation--active' : ''}`}
onMouseDown={onAnnotateStart}
ref={annotatingRef}
></canvas>
);
};
}