When I was growing up I had a PC in the house that we all shared, a “family computer.” We had slow internet, not many games and I know it sounds boring but one of my favorite things to do was to try out screensavers, change the audio theme, and check out new system display themes. With that said I’ve always been fascinated by the “mystify” and of course the famous “3d maze” screensavers.

If you aren’t familiar with these screensaver check out the video below.

PixiJS is awesome, it’s formally called “a HTML5 Creation Engine.

I recently started diving back into Javascript animations again and thought that trying to recreate the “Mystify” screensaver would be a nice challenge. Enter PixiJS.

PixiJS sits over the browser’s canvas API and made it a snap to focus more on the code for drawing the animation… rather than the ceremony of spinning a 2d canvas context, etc. Check out their examples on their website (here), it truly makes things a breeze and reminds me of easel.js/create.js.

What was my approach?

We have to remember that for canvas API we are simply drawing lines IN ONE GO. Think of it like a contour line drawing where we using one pen to draw our ENTIRE image.

via GIPHY

The code has Three “for loops” that work together to ensure we draw everything properly. Here’s a visual breakdown of how the algorithm makes it work.

1. Loop around for the amount of “points” we want in our drawing.

We have 5 points max defined in our constant (POINT_AMOUNT), so loop 5 times and create 5 point objects, and put them into an array. We go to each point in the array, drawing lines between them, and then lastly close our shape off by returning to the first point in the array. It’s important to note each point has a `x-velocity` and a `y-velocity` that we use on each timer “tick” (or draw frame) to move our points.

2. Pick the first point and try to loop down it’s positions

We start by grabbing the first point in the array, each point object has another child array included in it called “positions.” Think of these as levels/floors in a building. An important note is for the first item in the positions array we are “unshifting” new values onto the array (making it essentially a queue). We will use this queue pattern to keep all the prior {x,y} values while it’s animating. At the same time in our queue, we maintain a max array length of 5 levels that we loop for each point in the array.

3. Loop around and draw again at each “level”

Now we simply just draw our shape again at this level in the array. Rinse and repeat as shown below!

Fork it!