HTML5 Canvas Optimisation

5 Feb 2019

I wanted to create a custom image slider for my homepage that fit the design of my site. Initially there were performance issues but these are some of the optimisation techniques I found while making the image slider for my homepage.


When creating the image slider, I split the image into seperate pieces by drawing paths and clipping the image. These pieces were then animated to move each frame. Initially I was calculating these paths for each frame which slowed down the framerate. It barely worked on mobile devices since it also need to calculate the drop shadow behind the shape.

To reduce the number of calculations that are required, I only created the shapes once. I did this by creating a canvas for each shape and then hiding the canvas so users can’t see them on the screen. I could then retrieve the images from these canvases and draw them on the main canvas.

I could also reduce the number of separate shapes when blending from one image to the next by taking a snapshot of the canvas before it transitions to the next slide. That way I don’t need to store the pieces from the previous slide. This also allowed the slide to be interrupted before it has completely transitioned.


After implementing sprites, I noticed that there was still a low framerate on my low-end mobile device. To solve this problem I used resolution scaling to reduce the resolution on phones.

To reduce the resolution of a canvas, all you need to do is set its width and height in pixels. You can then use CSS to scale the canvas to fit the screen correctly. I also reduced the resolution of the separate pieces so they take less time to create as well.

The lower resolution takes even less time to compute so it is extremely fast but you lose some of the detail in the image. So if your project is computationally intensive, you might need to sacrifice some of the resolution to increase the framerate.

Since it was only the mobile devices that had problems with the higher resolution, I only reduced the resolution for smaller screen sizes. This also means that high end phones also receive the low-res version. For further improvements, I think it would be a good idea to dynamically adjust the resolution based on how fast the device can draw frames.