pixi-fusion
Version:
This module offers a set of common components needed for playing games.
70 lines (69 loc) • 2.4 kB
JavaScript
import React, { createRef, useEffect, useMemo, useState } from "react";
import { Application } from "pixi.js";
import { WorldContext } from "./World.context";
import { Stage } from "../stage";
import { AssetsManager } from "../assets-manager";
export const World = ({ children, eventMode, size }) => {
const canvasRef = createRef();
const [applicationRef, setApplicationRef] = useState(null);
const worldSize = useMemo(() => {
if (size) {
return { ...size };
}
if (canvasRef?.current) {
const { width, height } = canvasRef.current.getBoundingClientRect();
return {
width,
height
};
}
if (!applicationRef) {
return {
width: 0,
height: 0
};
}
return {
width: applicationRef.screen.width,
height: applicationRef.screen.height
};
}, [size, canvasRef.current, applicationRef]);
useEffect(() => {
if (!applicationRef) {
const application = new Application();
application.init().then(() => {
setApplicationRef(application);
});
}
}, []);
useEffect(() => {
if (applicationRef && canvasRef.current) {
applicationRef.resizeTo = canvasRef.current;
applicationRef.resize();
}
}, [canvasRef.current, applicationRef]);
const conextValue = useMemo(() => ({
application: applicationRef,
size: worldSize
}), [applicationRef, worldSize]);
useEffect(() => {
if (!applicationRef) {
return;
}
canvasRef.current?.appendChild(applicationRef.canvas);
return () => {
if (applicationRef) {
canvasRef.current?.removeChild(applicationRef.canvas);
}
};
}, [canvasRef.current, applicationRef]);
useEffect(() => {
if (applicationRef) {
applicationRef.stage.eventMode = eventMode;
}
}, [eventMode, applicationRef]);
return (React.createElement(WorldContext.Provider, { value: conextValue },
React.createElement(AssetsManager, null,
React.createElement(Stage, null, children),
React.createElement("div", { style: { width: "100%", height: "100%" }, ref: canvasRef }))));
};