HTML <canvas> Animation with Javascript

hui wang
3 min readSep 26, 2017

--

Example of an HTML canvas project: https://dollarakshay.com/particles.html

<canvas> is an HTML element that allows a user to create graphics using Javascript. It can be used to create animations, interactive graphics, and browser games.

Creating a new Canvas Project

To start a canvas project, we will need an HTML file and a Javascript file. In the HTML file, two lines of codes are required in the body.
<canvas id=”canvas” style=”border:1px solid black"></canvas>
<script src=”nameOfYourJSFile.js”></script>
This will create the canvas and connect the javascript to the HTML.

Bubble Maker — This is a interactive canvas I created.

Here is the link to the Javascript code for the gif above. https://gist.github.com/mypwhas9letters/1d5fcd68baae88125da8f4788c335b52

To start drawing, we will have to find the canvas in our Javascript file.
const canvas = document.querySelector(‘canvas’)

The canvas element comes with a default size of 300px by 150px. If we want the canvas size to be responsive, set the width and length equal to the user’s current browser size.
canvas.width = window.innerWidth
canvas.height = window.innerHeight

Next, we need access to the canvas’ methods. Define a variable and set it equal to canvas.getContext(‘2d’). This will allow the variable to use canvas methods to draw in 2d.
const brush= canvas.getContext(‘2d’)

Adding to the canvas

The canvas is a grid using pixels as coordinates. The top left most corner x = 0 and y = 0. x is the horizontal coordinate and y is the vertical coordinate.

To create a circle, we need to enter 5 parameters.
x -where to start on the x axis
y -where to start on the y axis
r -radius of the circle
startingAngle in radian
endingAngle in radian
brush.arc(x,y,r,startingAngle,endingAngle)

If we want to create a circle 100 px from the left and100 px from the top with a radius of 50, we can express it with
c.arc(100,100,50,0,2*Math.PI).

To instantiate multiple circles, we can create a function to construct them. For a circle to animate, we will need to define its velocity(dx and dy). If we set dx = 5 and dy = 5, the circle will move 5 pixels diagonally. It is adding 5 pixels to its x and y coordinate every refresh.

Next lets defined a function that will generate random colors.

To add interactivity to our canvas, we have need to add an event listener to our canvas.

Now we just need a function to add animation to our circles.

Your canvas should look like the gif above.

Sources:
https://www.w3schools.com/graphics/canvas_intro.asp
https://www.youtube.com/channel/UC9Yp2yz6-pwhQuPlIDV_mjA

--

--