Skip to content

Commit

Permalink
Fix canvas behavior on mobile
Browse files Browse the repository at this point in the history
- OffscreenCanvasRenderingContext2D doesn't seem to work on mobile
- Uncapped drawing FPS causes mobile canvas to crash
  • Loading branch information
imericxu committed Jul 11, 2024
1 parent fe923d6 commit d0959f5
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
7 changes: 6 additions & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,12 @@ export default function Home(): ReactElement {
ref={containerRef}
className="glass-surface mx-auto box-content h-0 w-0 rounded-2xl p-5 transition-all"
>
<canvas ref={canvasRef} className="h-0 w-0 transition-all">
<canvas
ref={canvasRef}
width={1}
height={1}
className="h-0 w-0 transition-all"
>
Your browser doesn&lsquo;t support HTML Canvas.
</canvas>
</div>
Expand Down
11 changes: 6 additions & 5 deletions src/lib/MazeDrawer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default class MazeDrawer {
/** The canvas rendering context. */
private visibleCtx: CanvasRenderingContext2D;
/** The hidden canvas rendering context for offscreen rendering. */
private hiddenCtx: OffscreenCanvasRenderingContext2D;
private hiddenCtx: CanvasRenderingContext2D;

private sweepAnimations = new Set<AnimationPromise>();

Expand All @@ -75,12 +75,10 @@ export default class MazeDrawer {
this.visibleCtx = ctx;
const hiddenCanvas = document.createElement("canvas");
this.hiddenCtx = match(
hiddenCanvas
.transferControlToOffscreen()
.getContext("2d", { willReadFrequently: true }),
hiddenCanvas.getContext("2d", { willReadFrequently: true }),
)
.with(null, () => {
throw new Error("Failed to create offscreen canvas.");
throw new Error("Failed to get hidden canvas context");
})
.otherwise((ctx) => ctx);
this.gridSize = initialGridSize;
Expand Down Expand Up @@ -222,6 +220,7 @@ export default class MazeDrawer {
drawnWidth = imageWidth;
},
() => drawnWidth === this.width,
60,
);
this.sweepAnimations.add(animation);
animation.start();
Expand Down Expand Up @@ -416,6 +415,7 @@ export default class MazeDrawer {
drawnWidth = drawWidth;
},
() => drawnWidth === this.width,
60,
);
this.sweepAnimations.add(animation);
animation.start();
Expand Down Expand Up @@ -462,6 +462,7 @@ export default class MazeDrawer {
drawnWidth = drawWidth2;
},
() => drawnWidth === this.width,
60,
);
this.sweepAnimations.add(animation);
animation.start();
Expand Down

0 comments on commit d0959f5

Please sign in to comment.