davidfig / pixi-viewport

A highly configurable viewport/2D camera designed to work with pixi.js
https://davidfig.github.io/pixi-viewport/
MIT License
1.04k stars 174 forks source link

Question: How to call pixi-viewport method from an outside component using react-pixi #233

Open fakob opened 4 years ago

fakob commented 4 years ago

Hi,

It might be a silly question as I am new to pixi-viewport or not belong here as I am using pixi-viewport with react-pixi, but I am trying to figure out how I can call viewport methods from an outside component. I know how to trigger it from within the viewport

viewport.on("click", () => {
      viewport.moveCenter(0,0);
      viewport.fit();
    });

Now I would like to trigger the same thing from a button outside the viewport. This is my base set up: https://codesandbox.io/s/romantic-bhabha-i0jpr?file=/src/index.js

I have tried accessing the viewport with useRef, but I seem to only get a reference to the stage.

Any idea what I am doing wrong?

spassvogel commented 4 years ago

One way to do it is to expose those events as properties.

interface Props {
  children: React.ReactNode;
  onClick?(event: ClickEventData): void;
  screenWidth: number,
  screenHeight: number,
  worldWidth: number,
  worldHeight: number,
  minScale?: number;
  maxScale?: number;
}

const PixiComponentViewport = PixiComponent("Viewport", {
  create: (props: PixiComponentProps & Props) => {
    const viewport = new PixiViewport({
      screenWidth: props.screenWidth,
      screenHeight: props.screenHeight,
      worldWidth: props.worldWidth,
      worldHeight: props.worldHeight,
      ticker: props.app.ticker,
      interaction: props.app.renderer.plugins.interaction,
    });
    viewport.on("clicked", (event) => { if(props.onClick) props.onClick(event) });

useRef is possible too but you have to use forwardRef then

fakob commented 4 years ago

Hi @spassvogel, thanks for the forwardRef tip. That worked perfectly. I have updated the sandbox example if anyone is interested.

Your other suggestion, I unfortunately could not wrap my head around. Maybe there was a misunderstanding. I am trying to call viewport methods such as

viewport.moveCenter(0,0);
viewport.fit();

from its parent component. As the forwardRef method worked fine, I continue with it. Thanks for the help!