ES6 Classes & Math.sin, Math.cos in Vanilla JS & HTML Canvas Animated Backgrounds Coding Tutorial

Hi everyone, welcome to another tutorial
in my vanilla JavaScript and html5 canvas animation series where we create
all different kinds of interactive animated backgrounds. In this episode I
will show you how to create spinning stars effect you can see on the screen
right now. There will be a lot of spinning in this video so hopefully you
don’t get dizzy easily. This is the fourth episode in my vanilla JavaScript
and HTML canvas animation series, if you missed the previous tutorials you can
find the links in the description down below. Everything in this series is coded
from scratch with HTML canvas and vanilla JavaScript, no libraries or
frameworks. I will quickly explain every line of the code and by the end of the
video you will be able to use these techniques for your projects. Don’t
forget to like the video if you liked it, subscribe to my channel and click the
bell icon to get notified when I release a new video. In this episode we have
three things to learn. First how to draw different shapes other than circles or
rectangles on canvas. Second is how to make particles spin around in circles
and the third – how to create particle trails.
I know these tutorials are getting quite advanced but if you are a beginner I
will do my best to explain every step as we build our code. This is advanced
JavaScript but it is beginner friendly. To draw the stars we will use quite
complex function that is reusable and can generate stars with any number of
spikes and also can generate shapes like hexagons. Making particles spin around in
circles is very easy. I will show you how to use cosine and sine trigonometric
functions to do that. There are multiple ways to make particles leave trails
as they travel around the canvas. In this video we will start with very simple one
line of code trick that achieves that. In later episodes I will show you more
complex and versatile way to do it. As usual if you stay until the end of the
video I will show you how to customize and modify this effect. As you can see I
built many many versions of this and I will teach you everything you need to
know to build these and many more yourself. For example I will show you how
to tweak the code to make smaller particles in the center so it creates
kind of a tunnel. Although don’t go crazy with your
customizations, not every idea as a good design. We will work with three files in
this project in index.html we just link style.css and script JS files and create
HTML canvas element with an ID of canvas 1. In style CSS we declare basic reset
rules and set position and size of our canvas. Let’s give it white background
this time. Everything else will be done in script JS file. Let’s get a reference
to the canvas element with get element by ID and save it in a variable I called
canvas. Then save context under CTX variable and give it a 2d property. Canvas width and height will be equal to
the size of our window. We also declare particle array, we will use it later to
store randomized particle objects. We will create this randomized particle
objects with es6 class i called particle with capital P. Every class needs a
constructor, which is a special method for creating and initializing an object
created with a class. We give it four arguments – moveRadius, step, position and
size. We will also need draw method which will interact with our canvas and draw
each particle at position we will pass to it. This is a custom method so you can
call it whatever you want. Inside we call begin path and canvas arc method. This
method takes at least five arguments and it will draw a simple circle on canvas.
Main arguments for us are the first two. These stand for the position on the x
and y axis. This is a big part of our circular motion animation. We will use
basic trigonometry. For x-position we will call Math.cos method. This
method by default rotates infinitely back and forth between minus one and
plus one, we will pass it this dot position attribute which we will later
set as a random number along a circle path. We multiply it by this.moveRadius which will increase the rotation of cosine (which is by default minus
one to plus one), it will increase that rotation to minus moveRadius to plus moveRadius. Then we add canvas width/2, this will set the
center of our circle in the middle of the canvas. So now we have our particles
rotating left to right between two positions, defined by its moveRadius
value. Second argument is for the Y position we will use math dot sine
function and do the same thing but for the canvas height. Now we have these two
methods pulling on our particles in a way that will result in a circle motion
if we increase this dot position property. Don’t forget to close path, fill
style will be white. Another custom method we will need on our particle
class I called update. The only job it has is to increase particles
position by particles step value and then call draw method to draw our circle
at the new position. Then we step out from the particle class and create a
top-level function I called init. This functions job is the fill particle array
we created earlier with particles with randomized values, based on the template
we set in the particle class constructor. First we set particles array to an empty
array in case it’s not empty at the moment. Then we create a for loop, the
number here will indicate how many particles we create, let’s do 500 at this
time. Move radius will be a random number between 0 and canvas width, this will
define the size of our entire rotating particles area. You can try and use much
smaller number here for example canvas width divided by 4. That will create a
small circle of rotating particles in the center of our canvas. Step will be a
small random number, this will be particle speed, because we are adding
this number to particles position in the update method. Position will be a random
number along circle area – math dot pi times 2. If you remember in draw method
we pass this number to sine and cosine multiplied by particles move radius
property and set Center as the middle of our canvas this will cause the particles
to spin around in circular motion size will be a random number between two
values bigger the values bigger the particles then we push these four
variables into our particles array by calling new keyword on our particle
class new keyword will create a new particle object with our randomized
values for loop will do this 500 times I create another function and call it
animate we will call requestanimationframe api for smooth
animation which will call itself recursively over and over
normally here I would call clear rect to clear our canvas after every step of
animation but we want our particles to leave trails as they move so instead
after every step of animation I will draw a semi-transparent rectangle the
size of our canvas our GBA stands for red green blue and alpha for value alpha
is opacity the lower the number you put here the longer trails particles will
leave then we create a for loop that will loop over the length of our
particle array and call update method for each particle in the array then I
call init to initialize new particle array and
fill it with particle objects with randomized values and I call animate to
set things in motion I made few typos here let’s fix
parentheses after math dot random parentheses in canvas arc method and
begin path needs to be called on context for it to work sorry about this you
probably noticed it as I was typing it out in the first place we are not done
yet as you can see the canvas stretches when we resize the window to fix that we
create an event listener for resize event and pass it a callback function
that will set canvas width and height to the current window size and init
function to create new particles array with position values adjusted to the new
canvas size if you decrease alpha value we will get longer trails behind
particles let’s make the particles bigger I like this effect it looks kinda
3d we can also use stroke instead of fill we are of course not done yet in the
this video is called spinning stars so how do you draw a star on canvas we will
have to do it as a custom shape but let’s make it as a reusable method that
way we can create all kinds of stars and even other shapes like hexagons octagons
and so on let me show you how I will call the function draw star it will take
five values position X position Y spikes outer radius and inner radius this
function will basically rotate around in a circle and draw paths that will create
our final shape the final shape will depend on the number of spikes we pass
to it and the difference between its inner and outer radius this video is
already running long if you are interested I can explain this in detail
in another video let’s see what the outcome looks like first i will decrease
the number of particles because drawing stars is a bit more demanding on the
system than drawing circles we want smooth animation up here in the draw
method i will extract X&Y position in two separate variables for clarity i
should have done this in the first place then instead of Arc method we will call
our custom draw star function we will pass it x and y so it rotates around
number of spikes can be four outer radius will be this.size and inner radius
will be this.size divided by 2 there we go we are drawing stars let’s make
them bigger and use fill instead of stroke we can also increase the number of
spikes watch what happens if we make out radius and inner radius
the same value we are no longer drawing star shapes the shape of the star depends on the
proportions between inner radius and outer radius values we can also change the background by
changing the fill style here let’s change the shape back to a circle
we can also easily customize the movement with the power of trigonometry
we can change the way the particles move now I declare variable I call wobble and
set it to 1 we will be increasing this variable every time we call draw wobble
basically represents time since math dot sine is very predictable and rotates
between two values if you know the time value you will be able to predict the
current position of sign I won’t go deeper into this in this
video but we will get back to it let’s just add sine here to our x value and
pass it wobble that’s too fast slow it down let’s do the same for Y and use cosine
instead slow it down even more and here we go you can also do other movement patterns
like this for example I’ll show you other tricks with trigonometry next time if we go a few steps back in our code I
can also show you how to make particles in the center smaller and getting larger
as the distance from the center grows to do that we can simply pass the value of
move radius instead of our this size value so that’s all done for today thank
you very much for watching don’t forget to like the video if you liked it
subscribe to the channel and click the bell icon to get notified when I release
a new video see you next time

Add a Comment

Your email address will not be published. Required fields are marked *