I am trying to implement a joystick that can be used to control something like a robot in React.JS using the React-Konva library. Thus far I have managed to get something that sort of works by drawing a smaller circle inside a larger one and letting the smaller circle track the mouse position relative to the stage while the mouse is down. The problem with it is that once the mouse leaves the stage, I stop getting the onMouseMove events and the circle is stuck at its last position until the mouse returns to the stage. Ideally I would like to be able to have the circle keep tracking the direction of the mouse even when it moves outside the stage, but obviously limit how far the circle can actually move from the origin to remain within the stage.
Here is the code I have so far
import React, { useState, useContext } from "react";
import { Stage, Layer, Circle } from "react-konva";
export default function Joystick(props) {
const { size } = props;
const [x, setX] = useState(0);
const [y, setY] = useState(0);
const [down, setDown] = useState(false);
const joyX = down ? x : size / 2;
const joyY = down ? y : size / 2;
return (
<Stage
width={size}
height={size}
onMouseMove={(ev) => {
setX(ev.evt.layerX);
setY(ev.evt.layerY);
}}
onMouseDown={(ev) => setDown(true)}
onMouseUp={(ev) => setDown(false)}
>
<Layer>
<Circle x={size / 2} y={size / 2} radius={size / 2} fill="black" />
<Circle x={joyX} y={joyY} radius={size / 4} fill="white" />
</Layer>
</Stage>
);
}
So what I'd like to know is what is the simplest and cleanest way that I can extend this to keep tracking the mouse even when it goes beyond the stage?