Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import React, { useCallback, useEffect, useState } from "react"; import { useAppSelector } from "store/hooks"; import { DMG_PALETTE, TILE_SIZE } from "consts"; import { tilesetSelectors } from "store/features/entities/entitiesState"; import TilePreviewWorker, { TilePreviewResult } from "./TilePreview.worker"; import { assetURL } from "shared/lib/helpers/assets"; import { GridUnitType } from "shared/lib/entities/entitiesTypes"; interface TileCanvasProps { tilesetId: string; tileIndex?: number; tileSize?: GridUnitType; } const worker = new TilePreviewWorker(); export const TileCanvas = ({ tilesetId, tileIndex, tileSize, }: TileCanvasProps) => { const size = tileSize === "16px" ? 2 : 1; const width = TILE_SIZE * size; const height = TILE_SIZE * size; const [workerId] = useState(Math.random()); const canvasRef = React.useRef<HTMLCanvasElement>(null); const tileset = useAppSelector( (state) => tilesetSelectors.selectById(state, tilesetId) ?? tilesetSelectors.selectAll(state)[0] ); const onWorkerComplete = useCallback( (e: MessageEvent<TilePreviewResult>) => { Iif (e.data.id === workerId) { const offscreenCanvas = document.createElement("canvas"); const offscreenCtx = offscreenCanvas.getContext("bitmaprenderer"); Iif (!canvasRef.current || !tileset || !offscreenCtx) { return; } const ctx = canvasRef.current.getContext("2d"); Iif (!ctx) { return; } offscreenCtx.transferFromImageBitmap(e.data.canvasImage); ctx.clearRect(0, 0, width, height); ctx.drawImage(offscreenCanvas, 0, 0); } }, [height, tileset, width, workerId] ); useEffect(() => { worker.addEventListener("message", onWorkerComplete); return () => { worker.removeEventListener("message", onWorkerComplete); }; }, [onWorkerComplete]); useEffect(() => { Iif (!canvasRef.current || !tileset) { return; } const ctx = canvasRef.current.getContext("2d"); Iif (!ctx) { return; } const tilesetURL = assetURL("tilesets", tileset); worker.postMessage({ id: workerId, src: tilesetURL, palette: DMG_PALETTE.colors, tileIndex, tileSize, }); }, [canvasRef, tileIndex, tileSize, tileset, workerId]); return ( <canvas ref={canvasRef} width={width} height={height} style={{ imageRendering: "pixelated", width: 16 }} /> ); }; |