DEV Community

Cover image for Using Canvas in vanilla JavaScript
Bin
Bin

Posted on

Using Canvas in vanilla JavaScript

What is Canvas?

Canvas is HTML element which you could draw graphic or use it to create some fancy animations.

Setup Canvas

In order to setup a canvas in vanilla JavaScript, you need to add canvas element on HTML file.
image
and then using querySelector to select the element, and setup the size of your canvas and chose the dimensional of context you are going to use, below I using two-dimensional drawing context
image

Basic Shape

1. Line

We need beginPath() to set a new path and using MoveTo() to create a sub-path of beginning of line and LineTo() to create a sub-path of ending of line. The strokeStyle() is color of line, the stroke() to drawing the line

image
image

2. Circle

Similarly, in order to drawing a circle on Canvas, we need beginPath() to set a new path, then using the arc() to create circular arc which require 6 parameters, 1st parameters is x-axis of arc's center, 2nd parameters is y-axis of arc's center, 3rd parameters is radius, 4th parameters is start angle, 5th parameters is end angle (below Math.PI *2 = 360°), the last parameters is determining if drawing the arc counter-clockwise between the start and end angles. The The strokeStyle() is outline color of circle , the stroke() to drawing outline of circle

image
image

3. Rectangle

The fillStyle() to set to set the color of rectangle and The fillRect() to create a rectangle

image
image

Reference:
Line Circle Rectangle More

Top comments (1)

Collapse
 
rakibsardar profile image
Rakib sardar

Hi am Rakib sardar and I am working on Rs library for game development are you want to work with this project