All Articles

Canvas maze

One day I found a picture of a maze in a webcomic. Seeing this maze, I wondered if I could turn it into an interactive maze game playable on a computer — something where the user could control a moving object that is blocked by walls.

I figured that I if I could extract the pixel data, then the dark pixels could count as walls. I looked around and found ctx.getImageData. This meant it was possible to make the maze game using html canvas, so I did.

One challenge was to keep the movement smooth in areas with curved or bumpy walls. I ended up using a formula where nearby walls repel the mover (a bit like electrostatic force). I added a circle maze to demonstrate the effect. Another challenge was that it was fairly CPU-intensive to run in the beginning. Then I made some optimisations such as not clearing the canvas and not recalculating nearby walls every frame.

circle maze

A goal was to make it work for images in general, including svg files such as the circle maze. I also added the ability for users to upload their own image. However, the URL option often fails due to CORS policy.

Bonus maze: Canva maze (I designed this maze shortly before starting work at Canva. It’s based on the company logo. The maze name was just so similar to “canvas maze”.)

Some features could be added and improved. For example, I haven’t yet added custom starting locations for the custom mazes, and the site could be made more responsive.