tutorialstonight logo
A Platform To Learn To Code

HTML CANVAS



The canvas is an element of HTML5 which is used to draw Graphics on the webpage.

The Graphics are created using javascript as scripting language.

Using canvas you can combine photos, create geometrical shapes, create animation, text etc.

The default size of canvas is 300px × 150px (height × width) but height and width can be changed using height/width attribute.


Basic canvas creation

Syntax:

<canvas id="your-id" height="value" width="value" ><canvas/>

since the default canvas created is blank and has no border. So to make canvas visible we can create a border.

Example

Run the code

Output:



filling color in canvas

The canvas is by default white in color which can be given any color value.

To fill a color in a rectangle we use the function fillStyle = "color_name" .

To fill a rectangle we use the function fillRect ( left_padding, top_padding, width, height) .

Example

Run the code

Output:

your browser do not support canvas.

Drawing a line using canvas

To draw anything on canvas we have to use javascript.

First we need to select the target canvas we want to use by id value.

Then we define context for the canvas (2d or 3d) using getContext.

Example

Run the code

Output:

your browser do not support canvas.

Drawing a circle on canvas

To draw a circle on canvas we use arc() method.

The arc() method takes five arguments: arc( x, y, r, start, stop).

Example

Run the code

Output:

your browser do not support canvas.