How to rotate particles and images on HTML canvas

In today’s front end web development project tutorial we will talk about rotating shapes, images and particles with plain vanilla JavaScript on HTML canvas. It can be tricky for beginners, because the concept of how it works is completely different from rotating elements with just CSS. It is very simple if explained properly so that’s what we will do today. Today we will build a beginner friendly particle system project together from scratch and in the process we will learn how to replace particles with images using draw image canvas 2d api method and how to make these images rotate around using 4 built in canvas methods – save, translate, rotate and restore. Let’s bring our HTML canvas projects to the next level by mastering these techniques, welcome to another episode of my vanilla JavaScript creative coding series.

In my previous frontend developer courses for absolute beginners I have been avoiding rotating elements and particles, except when creating fractal trees and fractal snowflakes, where I used similar technique we will use today to rotate a line around to create fractal patterns. The big reveal about HTML canvas rotation is, we can’t rotate individual elements, particles or images on canvas. We have to do a trick to achieve it. We will give JavaScript coordinates where the particle we want to rotate is, we save the current state of canvas context, we translate center of canvas to center of that particle, we rotate the entire canvas context by converting degrees into radians and passing that to rotate function and then we restore the canvas to its previous state before rotation., It will happen so fast which will make it seem like the particle has rotated.

Have fun, happy Halloween 😀

Sample images:

Leave a Reply