Line data Source code
1 : import { useElementBounding } from '@vueuse/core'
2 :
3 : import type { LGraphCanvas } from '@/lib/litegraph/src/litegraph'
4 : import type { PointTuple as Point } from '@comfyorg/shared-frontend-utils/geometry'
5 : import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
6 :
7 2356 : let sharedConverter: ReturnType<typeof useCanvasPositionConversion> | null =
8 : null
9 :
10 : /**
11 : * Convert between canvas and client positions
12 : * @param canvasElement - The canvas element
13 : * @param lgCanvas - The litegraph canvas
14 : * @returns The canvas position conversion functions
15 : */
16 2356 : export const useCanvasPositionConversion = (
17 : canvasElement: Parameters<typeof useElementBounding>[0],
18 : lgCanvas: LGraphCanvas
19 : ) => {
20 10114 : const { left, top, update } = useElementBounding(canvasElement)
21 :
22 10114 : const clientPosToCanvasPos = (pos: Point): Point => {
23 632 : const { offset, scale } = lgCanvas.ds
24 632 : return [
25 : (pos[0] - left.value) / scale - offset[0],
26 : (pos[1] - top.value) / scale - offset[1]
27 : ]
28 : }
29 :
30 10114 : const canvasPosToClientPos = (pos: Point): Point => {
31 7888 : const { offset, scale } = lgCanvas.ds
32 7888 : return [
33 : (pos[0] + offset[0]) * scale + left.value,
34 : (pos[1] + offset[1]) * scale + top.value
35 : ]
36 : }
37 :
38 10114 : return {
39 : clientPosToCanvasPos,
40 : canvasPosToClientPos,
41 : update
42 : }
43 : }
44 :
45 38990 : export function useSharedCanvasPositionConversion() {
46 38990 : if (sharedConverter) return sharedConverter
47 846 : const lgCanvas = useCanvasStore().getCanvas()
48 846 : sharedConverter = useCanvasPositionConversion(lgCanvas.canvas, lgCanvas)
49 846 : return sharedConverter
50 : }
|