嘿,我是反应 konva 的新手,想创建一个动画,其中一个矩形遵循用户定义的点路径。第一个用户通过单击屏幕并初始化目标点来定义路径,然后矩形应相应地跟随路径
const [coords, setCoords] = useState([]); //path dots variable
const [points, setPoints] = useState([250, 250]); //rectangle x,y variable
const ref= useRef(null);
const [check, setCheck] = useState(false); //check wheather user has clicked the start tracing button
const [i, setI] = useState(0); //index state variable
const handleStart= () => {
if (check === false) {
setCheck(true);
} else {
setCheck(false);
}
};
const handleClick = (e) => {
if (check === false) {
var stage = e.target.getStage();
var newcoord = stage.getPointerPosition();
var temp = [newcoord.x, newcoord.y];
setCoords((coords) => [...coords, temp]);
}
};
useEffect(() => {
if (!check) {
return;
}
var node = ref.current;
var anim = new Konva.Animation(function (frame) {
if (frame.time / 10 >= coords[i][0]) {
alert("reached");
setPoints([coords[i][0], coords[i][1]]);
setI(i + 1);
} else {
node.x(frame.time / 10);
}
if (frame.time / 10 >= coords[i][1]) {
alert("reached");
setPoints([coords[i][0], coords[i][1]]);
setI(i + 1);
} else {
node.y(frame.time / 10);
}
}, node.getLayer());
anim?.start();
return () => anim?.stop();
}, [check, i]);
return (
<div>
<Stage
onMouseDown={(e) => handleClick(e)}
width={window.innerWidth}
height={window.innerHeight}
>
<Layer>
<Group >
<Rect
width={50}
height={50}
x={points[0]}
y={points[1]}
strokeWidth={2}
fill="black"
opacity={1}
draggable
ref={ref}
/>
</Group>
{coords.map((key, index) => (
<Circle
x={key[0]}
y={key[1]}
numPoints={1}
radius={4}
fill="black"
strokeWidth={2}
/>
))}
</Layer>
</Stage>
<Button onClick={handleStart}>Start Tracing</Button>
</div>
这是我的代码,但它似乎没有按预期工作。非常感谢任何帮助。PS如果您有任何疑问请让我知道