# Recolouring an HTML Canvas.

I don't need this code anymore, but it was somewhat hard-fought to get right so I'm keeping it here for reference.

  /**
   * React hook for getting a recolored grid.  Recoloring the grid happens asynchronously,
   * so this hook wraps that into a synchronous-usable hook.  It will begin null and eventually resolve as an
   * OccupancyGrid.
   */
  public static useRecoloredGrid(grid: OccupancyGrid): OccupancyGrid | null {
    const [recoloredGrid, setRecoloredGrid] = useState<OccupancyGrid | null>(null);

    useEffect(() => {
      async function remap() {
        const remapped = await OccupancyGrid.remapColors(grid);
        setRecoloredGrid(remapped);
      }

      remap();
    }, [grid]);

    return recoloredGrid;
  }

  public static remapColors(grid: OccupancyGrid): Promise<OccupancyGrid> {
    if (recoloredCache.has(grid.id)) {
      return Promise.resolve(recoloredCache.get(grid.id)!);
    }

    const colorMap = new Map([
      [255, [80, 80, 80]],
      [205, [0, 0, 0]],
      [0, [0, 0, 0]],
    ]);

    return new Promise((res) => {
      const myCanvas = document.createElement("canvas");
      myCanvas.width = grid.width;
      myCanvas.height = grid.height;
      const ctx = myCanvas.getContext("2d")!;
      const img = new Image();
      img.onload = function () {
        ctx.drawImage(img, 0, 0); // Or at whatever offset you like

        // Remap the data.
        const imageData = ctx.getImageData(0, 0, grid.width, grid.height);
        for (let x = 0; x < grid.width * grid.height; x++) {
          const pixelValue = imageData.data[x * 4];

          const newColor = colorMap.get(pixelValue);

          if (newColor) {
            const [r, g, b] = newColor;
            imageData.data[x * 4] = r;
            imageData.data[x * 4 + 1] = g;
            imageData.data[x * 4 + 2] = b;
          }
        }

        ctx.putImageData(imageData, 0, 0);

        const data = myCanvas.toDataURL().replace(PNG_DATA_URL_HEADER, "");
        recoloredCache.set(grid.id, { ...grid, data });
        res({ ...grid, data });
      };
      img.src = PNG_DATA_URL_HEADER + grid.data;
    });
  }