All files / repo/src/hooks useCanvasRenderer.ts

86.53% Statements 45/52
84.61% Branches 11/13
100% Functions 5/5
86.53% Lines 45/52

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  1x     1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x   2x 4x   5x 1x 1x   1x 1x   1x   1x 2x 1x 1x 1x 1x 1x   1x                 1x 1x   1x 1x   5x 1x 1x 1x   5x 5x 5x 5x 5x 5x  
import type { Tile } from '@/components/GameCanvas/GameCanvas.types';
import { drawBoard } from '@/shared/utils/canvasRenderer';
import type { Ref } from 'vue';
 
export function useCanvasRenderer(
  canvasRef: Ref<HTMLCanvasElement | null>,
  tiles: Ref<Tile[]>,
  mouseX: Ref<number>,
  mouseY: Ref<number>,
  hoveredTileId: Ref<number | null>,
  tileSize: Ref<number>,
  applyTileLayout: () => void,
  fadeStartTime?: Ref<number | null>
) {
  function redrawCanvas() {
    const canvas = canvasRef.value;
    const ctx = canvas?.getContext('2d');
    if (!canvas || !ctx) return;
 
    drawBoard(ctx, canvas, tiles.value, { x: mouseX.value, y: mouseY.value }, hoveredTileId.value, tileSize.value, fadeStartTime);
  }
 
  function startAnimationLoop() {
    let lastRenderTime = 0;
    const FRAME_INTERVAL = 1000 / 90;
 
    function loop(currentTime: number) {
      const delta = currentTime - lastRenderTime;
 
      let shouldRedraw = false;
 
      tiles.value.forEach((tile) => {
        if (tile.matched && tile.haloAngle !== undefined) {
          const previousAngle = tile.haloAngle;
          tile.haloAngle = (tile.haloAngle + 0.03) % (Math.PI * 2);
          if (tile.haloAngle !== previousAngle) shouldRedraw = true;
        }
      });
 
      if (delta >= FRAME_INTERVAL && shouldRedraw) {
        const canvas = canvasRef.value;
        const ctx = canvas?.getContext('2d');
        if (canvas && ctx) {
          drawBoard(ctx, canvas, tiles.value, { x: mouseX.value, y: mouseY.value }, hoveredTileId.value, tileSize.value, fadeStartTime);
          lastRenderTime = currentTime;
        }
      }
 
      requestAnimationFrame(loop);
    }
 
    requestAnimationFrame(loop);
  }
 
  function layoutAndRedraw() {
    applyTileLayout();
    redrawCanvas();
  }
 
  return {
    redrawCanvas,
    startAnimationLoop,
    layoutAndRedraw,
  };
}