Line data Source code
1 : import type { Point2D as Point } from '@comfyorg/shared-frontend-utils/geometry'
2 : import { createSharedComposable } from '@vueuse/core'
3 : import { unref } from 'vue'
4 : import { useMaskEditorStore } from './maskEditorStore'
5 :
6 29 : function useCoordinateTransformInternal() {
7 29 : const store = useMaskEditorStore()
8 :
9 29 : const screenToCanvas = (clientPoint: Point): Point => {
10 229 : const pointerZoneEl = unref(store.pointerZone)
11 229 : const canvasContainerEl = unref(store.canvasContainer)
12 229 : const canvasEl = unref(store.maskCanvas)
13 :
14 229 : if (!pointerZoneEl || !canvasContainerEl || !canvasEl) {
15 0 : console.warn('screenToCanvas called before elements are available')
16 0 : return { x: 0, y: 0 }
17 : }
18 :
19 229 : const pointerZoneRect = pointerZoneEl.getBoundingClientRect()
20 229 : const canvasContainerRect = canvasContainerEl.getBoundingClientRect()
21 229 : const canvasRect = canvasEl.getBoundingClientRect()
22 :
23 229 : const absoluteX = pointerZoneRect.left + clientPoint.x
24 229 : const absoluteY = pointerZoneRect.top + clientPoint.y
25 :
26 229 : const canvasX = absoluteX - canvasContainerRect.left
27 229 : const canvasY = absoluteY - canvasContainerRect.top
28 :
29 229 : const scaleX = canvasEl.width / canvasRect.width
30 229 : const scaleY = canvasEl.height / canvasRect.height
31 :
32 : const x = canvasX * scaleX
33 : const y = canvasY * scaleY
34 :
35 229 : return { x, y }
36 : }
37 :
38 29 : const canvasToScreen = (canvasPoint: Point): Point => {
39 0 : const pointerZoneEl = unref(store.pointerZone)
40 0 : const canvasContainerEl = unref(store.canvasContainer)
41 0 : const canvasEl = unref(store.maskCanvas)
42 :
43 0 : if (!pointerZoneEl || !canvasContainerEl || !canvasEl) {
44 0 : console.warn('canvasToScreen called before elements are available')
45 0 : return { x: 0, y: 0 }
46 : }
47 :
48 0 : const pointerZoneRect = pointerZoneEl.getBoundingClientRect()
49 0 : const canvasContainerRect = canvasContainerEl.getBoundingClientRect()
50 0 : const canvasRect = canvasEl.getBoundingClientRect()
51 :
52 0 : const scaleX = canvasRect.width / canvasEl.width
53 0 : const scaleY = canvasRect.height / canvasEl.height
54 :
55 0 : const displayX = canvasPoint.x * scaleX
56 0 : const displayY = canvasPoint.y * scaleY
57 :
58 0 : const absoluteX = canvasContainerRect.left + displayX
59 0 : const absoluteY = canvasContainerRect.top + displayY
60 :
61 : const x = absoluteX - pointerZoneRect.left
62 : const y = absoluteY - pointerZoneRect.top
63 :
64 0 : return { x, y }
65 : }
66 :
67 29 : return {
68 : screenToCanvas,
69 : canvasToScreen
70 : }
71 : }
72 :
73 29 : export const useCoordinateTransform = createSharedComposable(
74 : useCoordinateTransformInternal
75 : )
|