In this article we will learn the following concepts related to the <canvas> tag:
- Basics of <canvas> Tag
- How to create <canvas> element
- How to Draw Basic Shapes on Canvas
Basics of <canvas> Tag
How to Create <canvas> Element
Let’s consider the below-given snippet to understand how to create a canvas element:
Here, id=canvas which will be utilized in the script to find the canvas element, width and height attributes set the canvas width and height as 250px and style attribute is used to style the canvas element.
Firstly we have to get the <canvas> element and for this purpose “getElementId()” method will be utilized as shown in the below code snippet:
Next, we will create a drawing object using a build-in object “getContext()” and inside this object, we will specify a dimension like 2-dimensional as shown in the below figure:
The final step is to draw on the canvas, we will specify a “fillStyle” property to set a color for the drawing:
How to Draw Basic Shapes on Canvas
This section will elaborate how to draw a rectangle, line, and circle on canvas:
To draw a rectangle on the canvas, we will utilize a fillRect() method. It will take four values: first for x-coordinate, second for y-coordinate, third for the width, and fourth for the height.
Here is our complete code snippet to draw a rectangle on canvas:
For the above code, we will get the following output:
As we specify 10px space for x, y coordinates so in the output the space around the top and left side verifies that our code works properly.
Now let’s consider another simple example to understand how to draw a line on a canvas. We utilize the moveTo() and lineTo() method to specify the initial and final points of the line respectively. To draw the line we have to use a method stroke() method:
On successful execution of the code we will get the following output:
A line is drawn on the canvas starting from (0, 0) and ending at (250, 150).
To draw a circle, we will utilize beginPath() and arc() methods to begin a path and create a circle respectively. The arc method will take values for the x, y coordinates, the radius of the circle, start angle, and end angle.
Math.PI property is utilized as the endpoint of the circle and the following will be the output:
In this section, we have learned how to draw basic shapes on canvas such as a line, circle, and rectangle.