next.js 如何在ReactFlow中使用Liveblocks创建实时光标,以实现准确的缩放,平移和不同的屏幕分辨率?

zzlelutf  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(101)

问题是,由于屏幕分辨率、缩放级别或由单个用户交互引起的ReactFlow元素的定位的差异,实时光标在其他用户屏幕上的位置无法准确表示。这些差异导致远程显示器上的实时光标的不正确对准,使其看起来错位或未对准。为了实现无缝协作,必须确保实时光标的位置在所有用户的屏幕上精确调整和同步,同时考虑各种因素,如分辨率,缩放级别以及用户与ReactFlow元素的交互。
我已经成功地解决了这个问题,根据缩放级别和ReactFlow在其他用户屏幕上的当前位置调整了实时光标的位置。

yhqotfr8

yhqotfr81#

//如下实现live cursor组件:

import { FC, useEffect } from "react";
import { useReactFlow } from "reactflow"
import useLiveBlocksStore from "@/stores/useLiveBlocksStore";
interface LiveCursorProps {
    cursorPos: { x: number, y: number };
}
const LiveCursor: FC<LiveCursorProps> = ({cursorPos }) => {
    const reactFlowInstance = useReactFlow()
    const {
        updateMyPresence,
        liveblocks: { others },
      } = useLiveBlocksStore()

    useEffect(() => {
        const position = reactFlowInstance.project({ x: cursorPos.x, y: cursorPos.y });
        //Liveblocks method to set the curren cursor positon
        updateMyPresence({
            cursor: { x: Math.round(position.x), y: Math.round(position.y) }
        })
    }, [cursorPos])
    return (
        <>
            {
                others.map((other) => {
                    if (other.presence.cursor == null) {
                        return null
                    }
                // get current Reactflow screen viewPort
                        const otherViewPort = reactFlowInstance.getViewport();

                    //fixing the x, y position of cursor in other screen inside of react flow
                    let xPos = other.presence.cursor.x * otherViewPort.zoom + otherViewPort.x;
                    let yPos = other.presence.cursor.y * otherViewPort.zoom + otherViewPort.y;

                    return (
                        /* The cursor component takes the x and y coordinates of the cursor 
                        and accurately displays it in the correct position on     other users' screens. */
                    <Cursor key={other.id} x={xPos} y={yPos} />
                    )
                })
            }
        </>
}
export default LiveCursor

字符串
将组件作为子组件传递给ReactFlow组件,并确保此组件的位置设置为绝对位置。

const [cursorPos, setCurosrPos] = useState({ x: 0, y: 0 })
const handleMouseMove = (event: React.MouseEvent) => {
    setCurosrPos({ x: event.clientX, y: event.clientY });
};
return <div style={{position:"absolute",left:0, top:0, overflowY:"auto", width:"100vw" height:"100vh"}}  >
    <ReactFlow
        fitView
        nodes={nodes}
        edges={edges}
        onMouseMove={handleMouseMove}
    >
        <div style={{zIndex:10,position:"absolute"}} >
            <LiveCursors cursorPos={cursorPos} />
        </div>
    </ReactFlow>
</div>

相关问题