To update the viewport properties like padTop
, padBottom
, x
, y
, height
, etc., after instantiating the Spine player in a React environment, you can directly modify the viewport
configuration of the player instance. However, the Spine player API does not provide a direct method to update the viewport after instantiation. Instead, you can dispose of the current player instance and create a new one with the updated configuration. Here's how you can modify your React component to achieve this:
const SpinePlayerComponent = ({
id,
animation,
skins,
padTop,
padLeft,
padBottom,
padRight,
}) => {
const playerDivRef = useRef<HTMLDivElement>(null);
const playerRef = useRef<SpinePlayer | null>(null);
const [isPlayerLoaded, setIsPlayerLoaded] = useState(false);
const skeleton = isPlayerLoaded && playerRef?.current?.skeleton;
const initializePlayer = () => {
if (playerDivRef.current) {
const spinePlayer = new SpinePlayer(playerDivRef.current, {
binaryUrl: 'test.skel',
atlasUrl: 'test.atlas',
animation,
showControls: false,
preserveDrawingBuffer: false,
alpha: true,
viewport: {
padTop: `${padTop}%`,
padBottom: `${padBottom}%`,
padLeft: `${padLeft}%`,
padRight: `${padRight}%`,
},
success: () => {
setIsPlayerLoaded(true);
},
error: (error) => {
console.error('Error initializing SpinePlayer:', error);
},
});
playerRef.current = spinePlayer;
}
};
useEffect(() => {
initializePlayer();
return () => {
if (playerRef.current) {
playerRef.current.dispose();
playerRef.current = null;
}
};
}, [padTop, padBottom, padLeft, padRight]);
useEffect(() => {
if (skeleton && animation) {
playerRef.current.setAnimation(animation);
}
}, [animation, skeleton]);
useEffect(() => {
if (skeleton && skins) {
const newSkin = new Skin('custom-skin');
skins.forEach((skinName) => {
newSkin.addSkin(skeleton.data.findSkin(skinName));
});
skeleton.setSkin(newSkin);
skeleton.setToSetupPose();
}
}, [skins, skeleton]);
return (
<div ref={playerDivRef} id={id} className="w-[500px] h-[500px]" />
);
};
In this setup, the player is re-initialized whenever the padding properties change, ensuring the viewport is updated accordingly.