Moved tokens to be relatively positioned and scaled to the current map

This commit is contained in:
Mitchell McCaffrey
2020-03-20 17:56:34 +11:00
parent c25566f682
commit 33ea19fef6
6 changed files with 136 additions and 66 deletions

View File

@@ -1,12 +1,13 @@
import React from "react";
import { Image, Flex, Box } from "theme-ui";
import React, { useRef } from "react";
import { Box, Image } from "theme-ui";
import Token from "../components/Token";
import ProxyToken from "../components/ProxyToken";
const mapTokenClassName = "map-token";
const defaultTokenSize = 48;
function Map({ imageSource, tokens, onMapTokenMove, onMapTokenRemove }) {
function Map({ mapSource, mapData, tokens, onMapTokenMove, onMapTokenRemove }) {
function handleProxyDragEnd(isOnMap, token) {
if (isOnMap && onMapTokenMove) {
onMapTokenMove(token);
@@ -17,43 +18,76 @@ function Map({ imageSource, tokens, onMapTokenMove, onMapTokenRemove }) {
}
}
const mapRef = useRef(null);
const rows = mapData && mapData.rows;
const tokenSizePercent = (1 / rows) * 100;
const aspectRatio = (mapData && mapData.width / mapData.height) || 1;
return (
<>
<Flex
<Box
className="map"
sx={{ justifyContent: "center", flexGrow: 1 }}
sx={{ flexGrow: 1, position: "relative", overflow: "hidden" }}
bg="background"
>
<Box
sx={{
position: "absolute",
top: 0,
left: 0,
right: 0,
userSelect: "none"
position: "relative",
overflow: "hidden",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)"
}}
>
{Object.values(tokens).map(token => (
<Box
key={token.id}
sx={{
position: "absolute",
transform: `translate(${token.x}px, ${token.y}px)`
}}
>
<Token
tokenId={token.id}
image={token.image}
className={mapTokenClassName}
/>
</Box>
))}
<Box
sx={{
width: "100%",
height: 0,
paddingBottom: `${(1 / aspectRatio) * 100}%`
}}
/>
<Box
sx={{ position: "absolute", top: 0, right: 0, bottom: 0, left: 0 }}
>
<Image ref={mapRef} id="map" src={mapSource} />
</Box>
<Box
sx={{
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0
}}
>
{Object.values(tokens).map(token => (
<Box
key={token.id}
style={{
left: `${token.x * 100}%`,
top: `${token.y * 100}%`,
width: `${tokenSizePercent}%`
}}
sx={{
position: "absolute",
display: "flex"
}}
>
<Token
tokenId={token.id}
image={token.image}
className={mapTokenClassName}
/>
</Box>
))}
</Box>
</Box>
<Image src={imageSource} sx={{ objectFit: "contain" }} />
</Flex>
</Box>
<ProxyToken
tokenClassName={mapTokenClassName}
onProxyDragEnd={handleProxyDragEnd}
size={defaultTokenSize}
/>
</>
);